A standard Unix command-line tool for piping to a socket
-
05-09-2019 - |
Question
I have some applications, and standard Unix tools sending their output to named-pipes in Solaris, however named pipes can only be read from the local storage (on Solaris), so I can't access them from over the network or place the pipes on an NFS storage for networked access to their output.
Which got me wondering if there was an analogous way to forward the output of command-line tools directly to sockets, say something like:
mksocket mysocket:12345
vmstat 1 > mysocket 2>&1
Solution
Netcat is great for this. Here's a page with some common examples.
Usage for your case might look something like this:
Server listens for a connection, then sends output to it:
server$ my_script | nc -l 7777
Remote client connects to
server
on port 7777, receives data, saves to a log file:client$ nc server 7777 >> /var/log/archive
OTHER TIPS
netcat
(also known as nc
) is exactly what you're looking for. It's getting to be reasonably standard, but not available on all systems.
socat
seems to be a beefed-up version of netcat, with lots more features, but less commonly available.
On Linux, you can also use /dev/tcp/<host>/<port>
. See the Advanced Bash-Scripting Guide for more information.
netcat will help establish a pipe over the network.
You may want to use one of:
- ssh: secure (encrypted), already installed out-of-the-box on Solaris - but you have to set up a keypair for non-interactive sessions
- e.g.
vmstat 2>&1 | ssh -i private.key oss@remote.node "cat >vmstat.out"
- e.g.
- netcat: simple to set up - but insecure and open to attacks
Everyone is on the right track with netcat. But I want to add that if you are piping into nc
and expecting a response, you will need to use the -q <seconds>
option. From the manual:
-q seconds
after EOF on stdin, wait the specified number of seconds and then quit. If seconds is negative, wait forever.
For instance, if you want to interact with your SSH Agent you can do something like this:
echo -en '\x00\x00\x00\x01\x0b' | nc -q 1 -U $SSH_AUTH_SOCK | strings
A more complete example is at https://gist.github.com/RichardBronosky/514dbbcd20a9ed77661fc3db9d1f93e4
* I stole this from https://ptspts.blogspot.com/2010/06/how-to-use-ssh-agent-programmatically.html