Can I pipe stdout on one server to stdin on another server?
This is an unabashed yes.
When one uses ssh
to execute a command on a remote server it performs some kind of fancy internal input/output redirection. In fact, I find this to be one of the subtly nicer features of OpenSSH. Specifically, if you use ssh
to execute an arbitrary command on a remote system, then ssh will map STDIN
and STDOUT
to that of the command being executed.
For the purposes of an example, let's assume you want to create a backup tarball, but don't want to, or can't, store it locally. Let's have a gander at this syntax:
$ tar -cf - /path/to/backup/dir | ssh remotehost "cat - > backupfile.tar"
We're creating a tarball, and writing it to STDOUT
, normal stuff. Since we're using ssh to execute a remote command, STDIN gets mapped to the STDIN
of cat
. Which we then redirect to a file.
A convenient way of piping data between hosts when you don't need to worry about security over the wire is using netcat
on both ends on the connection.
This also lets you set them up asynchronously:
On the "receiver" (really, you'll have two-way communication, but it's easier to think of it like this), run:
nc -l -p 5000 > /path/to/backupfile.tar
And on the "sender", run:
tar cf - /path/to/dir | nc 1.2.3.4 5000
A very powerful tool for creating uni- and bidirectional connections is socat
. For a short look at the possibilities, look at the examples in its manpage.
It replaces netcat
and similar tools completely and has support for ssl encrypted connections. For beginners, it might be not simple enough, but it is at least good to know that it exists.