As part of my job as product owner for everSENSE I sometimes need to diagnose problems at remote servers. My preffered way is to take access via SSH. But in many places, the server is behind a NAT router so I have to resort to the inelegant method of using Teamviewer. Don’t get me wrong. Teamviewer is a wonderful application. But once you have gotten used to the power and speed of the terminal, nothing else will do.

There is actually a way, that you can connect to a computer behind a NAT/firewall from any other computer. Its simple and elegant and can be done in under 5 minutes. You need either:

  • A Teamviewer connection to the remote PC (Yes! But it’s only to run a single command I promise!)
  • A User on the remote end AND
  • A Server with a Public IP (Let’s call this a relay PC)

From the remote computer’s terminal run the following command

$ ssh -fN -R 10022:localhost:22 user@relay-pc

Let’s break down what this did. The ssh and user@relay-pc opens and authenticates a SSH connection. -fN puts the shell session that will open into the background. -R opens what is called a reverse SSH tunnel with the Relay server in which 10022:localhost:22 will cause any request received on the 10022 of the relay server to be forwarded to port 22 of the Remote Server.

Now from your computer log into the Relay Server

$ ssh user@relay-pc-ip-address

And from this shell session create another shell session again connecting to the relay server itself but on its port 10022

$ ssh user@localhost -p 10022

NOTE: The user in user@localhost should be the user on the Remote Server not the Relay Server. The password/key used should similarly be for the Remote Server.

And VOILA! You have just obtained SSH access to a server behind a NAT router.