Scp over a proxy with one command from local machine?
I have my local.machine, the proxy.machine and target.machine. local.machine doesn't have direct contact with target.machine, but needs to go through proxy.machine.
I want to scp a file from target.machine to local.machine. Is this possible to do with just one command from local.machine?
You can do this with ProxyJump. put this in your ~/.ssh/config
file (creating the file if it does not exist):
Host target.machine
User targetuser
HostName target.machine
ProxyJump [email protected]
After saving the file, you can just use
ssh target.machine
any time you want to connect. Scp also will work as it also respects the ssh config file. So will Nautilus, if you're using GNOME and want to use a GUI.
Old Answer (for older versions of OpenSSH)
Host target.machine
User targetuser
HostName target.machine
ProxyCommand ssh [email protected] nc %h %p 2> /dev/null
You can now* do this as a one-liner, without requiring nc
anywhere:
scp -o "ProxyCommand ssh [email protected] -W %h:%p" [email protected]:file .
Explanation
pcreds
and tcreds
represent your proxy and target credentials if required (username
, username:password
, etc.).
This is possible because of a built-in netcat-like ability, removing the requirement for nc
on the intermediate host. Using ssh -W host:port
sets up a tunnel to the specified host and port and connects it to stdin/stdout, and then scp
runs over the tunnel.
The %h
and %p
in the ProxyCommand
are replaced with the target host and port from the outer scp
command, to save you having to repeat them.
For even more convenience, you can configure the proxy in your ssh configuration:
Host target.machine
ProxyCommand ssh [email protected] -W %h:%p
and from then on just do
scp [email protected]:file .
* since OpenSSH 5.4 - released March 2010
If you don't mind using rsync instead of scp, you can use the following one-liner:
rsync -v --rsh "ssh proxy.machine ssh" target.machine:/remote/file /local/dir/
(you'll need passwordless access to the proxy machine)
You can do it in one command, but you need netcat (nc) installed on the proxy machine:
ssh -o "ProxyCommand ssh [email protected] nc -w 1 %h 22" [email protected]
$ ssh -f -N -L <localport>:<target.machine:port> [email protected]
$ scp [email protected]:/remote/file -P <localport> .
OK, actually two commands...