Ubuntu – Use Outgoing SSH to receive incoming SSH

networkingremote accessssh

My ISP does not allow me to have a static IP address. As such I am unable to remotely SSH in my home machine. Is there a way I could SSH from my home machine to a server and SSH into the server from my remote laptop and bridge the two connections?


Best Answer

I just copy/paste (slightly modified) part of @b_laoshi's answer from here:

In this case, you can configure your ssh tunnel from ComputerA -> ComputerB such it can tunnel reverse connections as well.

When establishing the ssh connection ComputerA -> ComputerB, do so with the -R option in the following manner:

ssh ComputerBUser@ComputerB -R 2222:localhost:22

where ComputerBUser is the username for the account on ComputerB being authenticated and 2222 is a free port on ComputerB. We'll use this port to reverse-tunnel back to ComputerA from ComputerB.

Now from ComputerB, you can issue the scp command in the following manner to copy files from ComputerB -> ComputerA where ComputerAUser is your username on ComputerA:

scp -P 2222 /path/to/file/on/ComputerB ComputerAUser@localhost:/path/to/drop/file/on/computerA


ssh -p 2222 ComputerAUser@localhost

What's happening here?

It looks like we are simply telling ComputerB to send the file back to itself because we're passing localhost instead of ComputerA. We are indeed telling scp to pass the file back to ComputerB, but to port 2222. All connections to port 2222 on ComputerB get forwarded to port 22 (default ssh port) on ComputerA.

Thus, by tunneling backwards over the existing ssh connection, it doesn't matter that ComputerA is behind an NAT firewall.

EDIT: To allow to establish a SSH tunnel without the need for an active terminal window, one can add the -N parameter (before the -R) (as pointed out in the link provided by @steeldriver). Moreover, if one wants to automatically setup a permanent background ssh connection, Erik Torgesta's great article provides you with all the necessary steps.

Related topics:

Related Question