How can I pipe commands to a netcat that will stay alive?
echo command | netcat host port
This results in the command being sent to the remote host and some data being read back. But after a few seconds, the connection closes. The -w parameter did not change anything. I am using netcat v1.10 on SuSE 10.1.
Solution 1:
This works with the nc
command on OS X (assuming the command that you want to send is in a file):
cat file - | nc host port
(Essentially, cat
dumps the contents of file on stdout and then waits for you on stdin).
By extension, if you want to send the command from the shell itself, you could do this:
cat <(echo command) - | nc host port
Solution 2:
With nc
on Ubuntu:
nc -q -1 host port
From the Ubuntu nc
man page:
-q seconds
after EOF on stdin, wait the specified number of seconds and then quit. If seconds is negative, wait forever.
Note that the available nc
options vary a lot between distributions, so this might not work on yours (OpenSUSE).
Solution 3:
I found it:
echo command | netcat host port -
My coworker knew it. I don't see that in the documentation at all.
Solution 4:
Might it be that the connection is closed at the other end of the socket?
By default, nc
closes the connection after completion, if you don't explicitly tell him to stay listening (with the -k
option):
-k Forces nc to stay listening for another connection after its current
connection is completed. It is an error to use this option without the
-l option.
See man nc.1
.
I am successfully streaming data between two machines like this:
-
sender:
while (true); do echo -n "$RANDOM " | nc <host> <port> done
-
receiver:
nc -kl <port>
Solution 5:
I don't think you're going to manage this with either netcat or socat. I have just done extensive tinkering with both, and socat looked the most promising.
I managed to set socat up to connect to the remote TCP port and listen on a local unix domain socket (in theory so the link could be kept up all the time) but as soon as the local process detatched from the unix socket (another socat linking the unix socket to stdin/out) it closed the TCP socat session.
The problem here is that each connection through netcat / socat makes a new TCP stream connection to the server, and it closes that TCP stream session when the local end disconnects.
I think you're probably going to have to write some custom proxy software for this that opens the TCP connection to the remote end and then listens locally on a socket / pipe / fifo or whatever and then just sends the data down the existing TCP pipe and returns the results.