Reverse SSH tunnel to connect to device with dynamic IP

  • Picka = bannanaPi, raspberryPi, any othere device on dynamic IP
  • RemoteHost = server with static host, Picka can ssh to and you can ssh to that server from anywhere

on Picka do

ssh -N -R 2222:localhost:22 serverUser@RemoteHost

explanation of parameters of tunnel: ssh - shell command -N do not execute anything when connection successful -R bind port 22 on remote server [192.168.1.1] to 2222

so now connect to RemoteHost and

ssh -l pickaUser -p 2222 localhost

explanation of functionality

Why did this work? The RemoteHost is listening on port 2222 for incoming ssh connections. If it receives one, it will forward all traffic it receives into the previous ssh connection that was established already. That is essentially what the remote tunnel does.

persistent tunnel from Picka to RemoteHost

Now let’s take a step back and look at what we’ve done. When the Raspberri Pi is on, it will check every minute to see if an ssh connection to your linux server exists. If it doesn’t it will create one. The tunnel it creates is really a reverse remote tunnel. Once the tunnel is up, anyone who ssh’s into port 2222 of the linux server will then be redirected to the Pi. Incredible!

OnPicka

touch ~/ssh_tunnel.sh
chmod 700 ~/ssh_tunnel.sh
vim ~/ssh_tunnel.sh
  • add and save
#!/bin/bash -x
createTunnel() {
##### fill in vars
  RemoteHost="IP_HERE"
  ServerUser="NICK_HERE"
##### are wars filled?

  /usr/bin/ssh -N -R 2222:localhost:22 ${ServerUser}@${RemoteHost} &
  if [[ $? -eq 0 ]]; then
    echo Tunnel to RemoteHost IP: ${RemoteHost} created successfully
  else
    echo An error occurred creating a tunnel to RemoteHost IP: ${RemoteHost}. ReturnCode was: ${?}
  fi
}
/bin/pidof ssh
if [[ ${?} -ne 0 ]]; then
  echo Creating new tunnel connection to RemoteHost IP: ${RemoteHost}
  createTunnel
fi
  • add script to cron
crontab -e
  • and add (every minute check if the ssh connection is up, if not, attempt to bring it up)
*/1 * * * * ~/ssh_tunnel.sh > ~/ssh_tunnel.log 2>&1

Note for MAC users

* in case you have problem, that wiifi is turned off when screensaver is on * remember en1 should be replaced by your wiifi interface

cd /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources
sudo ./airport en1 prefs DisconnectOnLogout=NO
  • projects/ssh_reverse_tunnel.txt
  • Last modified: 2016/06/10 00:29
  • by over23