I am writing a script that ssh's into another machine and opens a netcat server. The server needs to be able to timeout.
netcat -w 3 throws the usage back at me.
How can I accomplish this?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
Here's a hack that can do what you want:
nc -l 12345 & NC_PID=$! ; sleep 3; if [ `netstat -ant | grep ':12345 .*ESTABLISHED'` -eq 0 ]; then kill -9 $NC_PID; fi
It starts the server, sleeps for whatever your timeout is, and then kills the netcat unless there is an established connection. There is a slight risk of having the server hang if there is an existing connection where the remote port matches your listener, but that would be bad luck.
Note: I tested this on a CentOS Linux, so the code is not fully portable, but the idea should be implementable on any *nix machine.