How to SCP from host to host from a central machine

Tags: , , , , , , ,

Time and time again I run into an instance where I have a file on host 1 and a file on host 2 but host 1 canโ€™t connect directly to host 2. Typically this requires me to copy the file locally to my desktop, then copy it again to the destination host. Thanks to the fact that ssh can tunnel standard input, however, there is a simple way to effectively scp directly from remote host to remote host using your machine as an intermediary. Hereโ€™s how.

SCP files using tar and ssh pipes

root@desktop ~ $ ssh host1 'tar -c ./foo' | ssh host2 'tar -x'

As you can see, we are simply redirecting the output of โ€˜tar -c ./fooโ€™ on host1 to โ€˜tar -xโ€™ on host2 through ssh. If you want to copy the file to a location other that your home directory on the remote server you can use something similar to the following.

root@desktop ~ $ ssh host1 'tar -c ./foo' | ssh host2 'cd /tmp; tar -x'

All we need to do is execute a cd command prior to our tar command to change the target of the copy.

I hope this helps! If you have a different way to do this leave a commend, I would love to hear it!