SSH reverse tunnel

From Urandom
Jump to: navigation, search

To create a ssh reverse tunnel you can use this command

ssh -f -N -C -R localhost:9922:localhost:22 user@host
* This will direct port 9922 on the remote machine back to port 22 on the client machine.
* You can omit the first localhost ( just 9922:localhost:22 ) then the remote host will listen on all interfaces.
* Ofcourse you can change the localhost to something of your needs.

Automated script for a permanent tunnel

* I use this script if something hapens to our VPN and i need to access my workplace, but don't want it to be active all the time.
#!/bin/sh

#SSH connection parameters
ssh_connect="user@example.com"
ssh_from="localhost:9922"
ssh_to="localhost:22"

#The web server to check for
check_host="https://example.com/checkfile"
#What the file has to contain(must be a number)
check_password="43642575"

while [ 0 -le 1 ]
do
        running=1
        ps -ef |grep "ssh -f -N -C -R $ssh_from:$ssh_to $ssh_connect" | grep -v grep -q || running=0
        shouldirun=`curl -sk $check_host`
        if [ "$shouldirun" -eq "$check_password" ]
        then
                if [ $running -eq 0 ]
                then
                        echo "`date` Starting SSH tunnel"
                        ssh -f -N -C -R $ssh_from:$ssh_to $ssh_connect
                fi
        else
                if [ $running -eq 1 ]
                then
                        echo "`date` Terminating SSH tunnel"
                        kill `ps -ef |grep "ssh -f -N -C -R $ssh_from:$ssh_to $ssh_connect" | grep -v grep | cut -d' ' -f3`
                fi
        fi
        echo -n "."
        sleep 60
done
* Checks if SSH tunnel is running or not.
* Checks if it should be running (compares the check_password to the contents of the check_host result)
* If the tunnel is down, but should be up then it starts it
* If the tunnel is up, but should be down then it kills it