I regularly transfer files from a second remote host to my local machine. It would be nice to do this in one go! However, I need to load a key to connect to the second remote host.
Usually, the process is first to connect to the intermediate host:
ssh user@host1
(enter password)
I then load my private key and transfer the file from the third host to the second host:
exec ssh-agent bash
ssh-add ~/.ssh/id-privatekey
scp user@host2:filename filename
Then finally exit the second host and transfer the file from the second host to my local machine
exit
scp user@host2:filename filename
This is time-consuming, and a bit of a pain for large files where the disk space on host1 is limited. The problem is similar to this question, so I tried:
ssh user@host1 'exec ssh-agent bash && ssh-add ~/.ssh/id-privatekey && ssh user@host2 "cat filename"' > filename
which seems to log into the first host, but nothing more. Please could anyone help?
Step 1
Given that you’ve already generated the normal public and private keys on the local machine, this copies the public key to the intermediate machine (in this case, intermediate_host) (remember to substitute your username for my_username).
ssh-copy-id -i ~/.ssh/id_rsa_remote.pub my_username@intermediate_host
This means that you only have to unlock your private key once (on your local machine) to log all the way in.
Step 2
Add the following (substituting your username) to your ~/.ssh/config file (or create the file if non-existent):
Host intermediate_nickname
Hostname intermediate_host
User my_username
IdentityFile ~/.ssh/id_rsa_remote
IdentitiesOnly yes
Host remote_nickname
HostName remote_host
User my_username
IdentityFile ~/.ssh/id_rsa_remote
IdentitiesOnly yes
ProxyCommand ssh -A intermediate_nickname -W %h:%p
Result
This means that:
ssh -A remote_nickname
logs straight into remote_host, and crucially:
scp remote_nickname:/remote/path/to/filename /local/path/to/filename
works to transfer a file from the remote host to your local machine.