How to scp via an intermediate machine?

I’d suggest the following in your .ssh/config:

Host C
    User user
    ProxyCommand ssh -W %h:%p user@B

I’t much safer if host B is untrusted, and works for scp and sftp.


As described in this answer, you can use the ProxyCommand directive to have an ssh host bounce you to a third host transparently:

Let's say you have the following three hosts:

  • workstation.example.com - This is the machine you're physically working on
  • proxy.example.com - This is the machine you're routing your SSH traffic through
  • endpoint.example.com - This is where you want the traffic to ultimately end up

In ~/.ssh/config on workstation, add the following:

Host endpoint
    User endpointUser # set this to the username on the endpoint host
    HostName endpoint.example.com
    ProxyCommand ssh [email protected] nc %h %p 2> /dev/null

On the proxy host, make sure nc (netcat) is installed.

Then, on workstation, you can ssh endpoint or sftp endpoint and you will be transparently proxied to the machine by way of your proxy host. scp will also work.


It's possible and relatively easy, even when you need to use certificates for authentication (typical in AWS environments).

The command below will copy files from a remotePath on server2 directly into your machine at localPath. Internally the scp request is proxied via server1.

scp -i user2-cert.pem -o ProxyCommand="ssh -i user1-cert.pem -W %h:%p user1@server1" user2@server2:/<remotePath> <localpath>

If you use password authentication instead, try with

scp -o ProxyCommand="ssh -W %h:%p user1@server1" user2@server2:/<remotePath> <localpath>

If you use the same user credentials in both servers:

scp -o ProxyCommand="ssh -W %h:%p commonuser@server1" commonuser@server2:/<remotePath> <localpath>

Tags:

Linux

Ssh

Scp