netcat doesn't print response

As @Patrick said, this problem is usually due to netcat exiting before the response has been given. You remedy that by adding -q 2 to the command line, i.e., tell netcat to hang around 2 seconds after detecting EOF on standard input. Obviously you can make it wait some other number of seconds as well.


Use this:

cat <(echo command) - | nc host port

The problem is that nc will close the connection immediately after stdin is closed, which is very quick for a simple my_command string, and thus never gets the chance to receive a response. (If you pipe a very large file you will see that it might get a response before it's done sending the file).

Enter cat with - as second argument: It makes cat listen on stdin for more content to pipe through after it has sent the contents of the first argument. The first argument is just getting the echo command through cat – it could also be a file with your commands a la cat < file - | ....

Alternatively do this:

(echo command; while true; do sleep 0.01; echo -n "#"; done) | nc host port

This sends unlimited # characters on the 2nd line of the input. Using # works for a bash like remote that would ignore this as a comment. I chose a small wait time of 10 milliseconds here, so it reacts faster on connection end. YMMV.

The downside of that can be that cat or the while loop and nc keep running until you hit ^C or ^D on the shell. It really depends on the remote end.

Adding a timeout using -w 1 (OSX netcat) or -i 1 (nmap's ncat) makes it close the connection and nc after 1 second, but cat will keep running until you enter some character and the pipe breaks (I think).

However, it works if the remote side will automatically close the connection after receiving and handling the command - this will also end the nc client and the process piping into it.

This answer is based on this this answer to an identical superuser question.

Tags:

Pipe

Netcat