I am writing a script that ssh's into another machine and opens a netcat server. The server needs to be able to timeout.

Using -l ignores -w.

The command netcat -w 3 throws the usage back at me.

How can I accomplish this?

  • timeout 3 thatcommandthatneedstotimeout – thrig Jan 27 '17 at 18:12

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.