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 kyle@127.0.0.1:~/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 kyle@127.0.0.1:~/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β¦
Top comments (0)