As a web developer, I’m often working with remote servers over SSH. Sometimes I’m working with a file on the remote server and want to get it back to my local machine (e.g. script output, a CSV, or a log file). One way I can easily get them back is by opening a reverse SSH port along my connection to the server.
tl;dr open a reverse connection to your local computer and
scp a file home
# from the remote shell, get into the SSH prompt $ <enter> ~C ssh> -R 127.0.0.1:2222:127.0.0.1:22 $ scp -P2222 move_this_file.txt email@example.com:~/Downloads
Let’s take a look at what’s going on here.
$ <enter> ~C
That’s the “enter” key, followed by a “tilde”, followed by a capital “C”. This string of keystrokes will get you into the
ssh command line and give you a new prompt.
ssh> -R 127.0.0.1:2222:127.0.0.1:22
From the new prompt we’re going to request a remote forward port…
ssh> -R 127.0.0.1:2222 :127.0.0.1:22
From the remote machine on port 2222…
ssh> -R 127.0.0.1:2222: 127.0.0.1:22
To the local machine on port 22.
Once this is set up, we can see a forwarded port opened on port 2222:
$ netstat -nap | grep 2222 tcp 0 0 127.0.0.1: 2222 0.0.0.0:*
We can then use this port to connect to the SSH server on the local machine and move any files using the scp command (or any command that can use the SSH connection).
$ scp -P2222 move_this_file.txt firstname.lastname@example.org:~/Downloads
In the case above, I’m sending the file named
move_this_file.txt to my local machine in my Downloads folder off my home directory.
When you close the SSH connection to the remote server, the port forward will also be closed.
If you’re on MacOS, you have an SSH server preinstalled on your machine that’s not active, you can turn it on from the command line:
$ sudo systemsetup -setremotelogin on
If you’re forward thinking enough, you can open this SSH remote port forward when you first connect to the remote server:
$ ssh -R 127.0.0.1:2222:127.0.0.1:22 remote_user@remote_server
I don’t usually anticipate that far ahead…