How to SCP from host to host from a central machine
Tags: copy, linux, pipe, scp, ssh, sysadmin, tar, unix
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!