How to scp with a second remote host

Double ssh

Even in your complex case, you can handle file transfer using a single command line, simply with ssh ;-)
And this is useful if remote1 cannot connect to localhost:

ssh user1@remote1 'ssh user2@remote2 "cat file"' > file

tar

But you loose file properties (ownership, permissions...).

However, tar is your friend to keep these file properties:

ssh user1@remote1 'ssh user2@remote2 "cd path2; tar c file"' | tar x

You can also compress to reduce network bandwidth:

ssh user1@remote1 'ssh user2@remote2 "cd path2; tar cj file"' | tar xj

And tar also allows you transferring a recursive directory through basic ssh:

ssh user1@remote1 'ssh user2@remote2 "cd path2; tar cj ."' | tar xj

ionice

If the file is huge and you do not want to disturb other important network applications, you may miss network throughput limitation provided by scp and rsync tools (e.g. scp -l 1024 user@remote:file does not use more than 1 Mbits/second).

But, a workaround is using ionice to keep a single command line:

ionice -c2 -n7 ssh u1@remote1 'ionice -c2 -n7 ssh u2@remote2 "cat file"' > file

Note: ionice may not be available on old distributions.


I don't know of any way to copy the file directly in one single command, but if you can concede to running an SSH instance in the background to just keep a port forwarding tunnel open, then you could copy the file in one command.

Like this:

# First, open the tunnel
ssh -L 1234:remote2:22 -p 45678 user1@remote1
# Then, use the tunnel to copy the file directly from remote2
scp -P 1234 user2@localhost:file .

Note that you connect as user2@localhost in the actual scp command, because it is on port 1234 on localhost that the first ssh instance is listening to forward connections to remote2. Note also that you don't need to run the first command for every subsequent file copy; you can simply leave it running.

Tags:

Scp