How to create a persistent port forwarding using ssh?

I am currently using ssh to forward few ports like this:

There are 3 machines:

  • A-host - machine building the tunnel, one that can access both B and C
  • B-host - machine that does not have access to A or C that that needs to be able to connect to C:636
  • C-host - machine providing a service on port 636

A-host>ssh -R 636:C-host:636 -R 8080:C-host:8080 root@B-host

The question is how to make this tunnelling be persistent, to restore it even one or another machine is restarted.

I know that this probably require autossh but that't not the entire solution.


Here is my current solution, if you know a better one, I will be grad to accept it.

On the machine that is initialting the tunnelling:

/etc/cron.d/autossh
@reboot autossh -f -nNT -R 3269:host-providing:3269 firewalled-host &

Now the firewalled-host can connect to localhost:3269 to access the service that was unavailable before.


Add the autossh command to a service that manages system services.

Most Linux setups use init, reading the configuration of what to start from /etc/inittab, a line something like rc:2:respawn:autossh <options> >>/var/log/autosshoutput 2>&1 would do the trick. That will (if you are in runlevel 2 which is the usual case for a running Linux system these days) start the process on boot and restart it if it dies. If you want it to start before the next reboot, run telinit to tell the init process to reread its config. See the man page for inittab for more details.

Some Linux distributions have moved to using upstart to manage what init used to (amongst upstart's other features, as it does more then init ever did) - you should find plenty of documentation on this easily.