Tag Archives: reverse-tunnel

Persistent Reverse-SSH Tunnels with autossh and screen

I’ve been working to manage my place remotely as I tend to have irregular hours. As a pilot I put in a Raspberry Pi and got a Belkin WeMo Switch. I had two problems with this setup;

  1. The internet connection is NAT-ed
  2. The Belkin cloud-y manager thing doesn’t seem to work (neither does IFTTT)

My solution was to use the RPi to manage the WeMo, and to have a reverse-ssh tunnel between the RPi and my public server.

  1. Ensure that passwordless SSH is working between the RPi and the server – plenty of guides online about how to do this.
  2. Open a screen session
  3. Use autossh to open and maintain the tunnel
$ autossh -M 65500 -o ServerAliveInterval=20 -R 11141:localhost:22 [email protected]

Autossh will use ports 65500 and 65501 to send echo data over and back between server and host, and opening an ssh session on the public server to local port 11141 will tunnel back to the SSH port on the RPi

ssh -p 11141 [email protected]

While this works fine, there is a potential issue – if the RPi is rebooted/looses power for any reason, the tunnel will be gone so we need to automate the setup so that it will be fired up upon boot – we will use a crontab entry for this:

@reboot /usr/bin/screen -S reverse-ssh-tunnel -d -m autossh -M 65500 -i /home/pi/.ssh/id_rsa -o "ServerAliveInterval 20" -o "ServerAliveCountMax 3" -R 11141:localhost:22 [email protected]

This cron entry will open a screen on reboot with “reverse-ssh-tunnel” as the title, and issue the autossh command. Reboot the RPi to test and you should be good to go.

Simples 🙂