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).
- 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
^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.