Home > bash, BashScripts, HowTo, Linux, LinuxCommands, script, Security > Reverse SSH Tunnel

Reverse SSH Tunnel

November 14th, 2016 Leave a comment Go to comments

The idea is to have my IP autostart connect to my Cloud server,
this way I can remote control my Raspberry PI without having to configure DynDNS and firewall rules.
The only requsisite is that PI has internet and run a simple script on startup to estabilish the SSH tunnel

The solution is to setup a Reverse SSH Tunnel, this will forward connection from my Cloud Server back to the PI
PS. My SSH is always on port 443
1. On Raspberry PI generate a SSH key and authorize connection to my server

2. Now we create a connection and keep it listening on port 2222
ssh -p 443 -N -R 2222:localhost:443 pi@

3. From Cloud Server to PI I can connect by doing:
ssh -l pi -p 2222 localhost

This is a simple script that can be set on crontab to run every 5min
*/5 * * * * /usr/bin/autoc.sh >> /var/log/autoc.log

Here is the script

#!/bin/bash
#
# Auto connect script
# Felipe Ferreira Oct 2016

# Requires user to authenticate with Key to be working

RHOST=felipeferreira.net
RPORT=443
RUSER=pi
LPORT=2222 # Local port to have SSH listen on Remote server just do ssh -l $RUSER $LPORT

connect() {
MSG="Tunnel to $RHOST $PORT $RUSER connection"
#nc -4 -v -w 2 $MAIL_RELAY 25 2>&1 |grep -c succeeded
if [[ $(/bin/nc -4 -z -v $RHOST $RPORT 2>&1 |grep -c succeeded) = 1 ]]; then

CMD="su - $RUSER -c '/usr/bin/ssh -o StrictHostKeyChecking=no -p $RPORT -N -R ${LPORT}:localhost:${RPORT} ${RUSER}@${RHOST} &'"
#echo $CMD
R=$(eval $CMD)
if [[ $? -eq 0 ]]; then
echo "OK - $MSG establisihed"
exit 0
else
echo "CRITICAL - $MSG Connection Failed"
exit 2
fi
else
echo "CRITICAL - $MSG is unreacheable, check internet connection and ${RHOST}:${RPORT}"
exit 2
fi
}

whoami

/bin/pidof ssh 2>&1 > /dev/null
if [[ $? -ne 0 ]]; then
connect
fi

  1. No comments yet.
  1. No trackbacks yet.
What is 12 + 9 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)

*