Running SCP Through an SSH Tunnel

Geronimo
1 min readOct 20, 2021

You want to copy a file from machine A to machine B, but machine A is only accessible through another machine, i.e., a gateway G?

Thanks to SSH, you can establish an SSH tunnel and directly pass the file from A to B!

This is how it works:

1. Step: Open a terminal/shell/command line and type:

$ ssh -L 1234:<IP-of-machine-A>:22 <user-on-machine-G>@<IP-of-machine-G>

2. Step: Open another terminal/shell/command line and type:

$ scp -P 1234 <user-on-machine-A>127.0.0.1:path/to/file path/to/destination

What happened?

In step 1, you connected to the gateway via ssh. The option -L 1234:<IP-of-machine-A>:22 specifies that port 1234 on your machine is forwarded to <IP-of-machine-A> on port 22. I.e., here you established an SSH tunnel from your local machine B through the gateway to machine A, using port 1234 on your machine and port 22 on the remote machine A.

In step 4, you copy the file from machine A to machine B using scp, pretending machine A was localhost (127.0.0.1) and would listen to you on port 1234. This works, because the SSH tunnel forwards 1234:127.0.0.1 to machine A port 22.

Go ahead. Try it out. Copy and paste: anything, from anywhere, to anywhere you want.

--

--