Automatic reverse ssh tunnel – Linux

Purpose: start/maintain/stop a reverse ssh tunnel to an always-on ssh accessible server

Naming conventions:

middleman is the ssh server that will be used to access the client machine

middleman has IP address mm.ip.addr

cuid and mmuid are users with access rights to ssh on client and middleman respectively

On client have nmap, autossh, openssh installed

On server have openssh-server installed and runnig

On client log in as cuid:

ssh-keygen # press enter twice for empty password

cat .ssh/ | ssh -l mmuid mm.ip.addr sh -c "cat – >> ~/.ssh/authorized_keys"

nano /etc/network/if-up.d/start_autossh_rev_tunnel



#echo Checking for autossh…

[ -x /usr/bin/autossh ] || exit 0

#echo Checking for ssh…

[ -x /usr/bin/ssh ] || exit 0

#echo Checking for nc…

[ -x /bin/nc ] || exit 0

#echo Checking for server…

[ ! `/bin/nc -z -w 1 22` ] || exit 0

#echo Stopping any already running autossh instances.

killall -q -TERM autossh

sleep 1

#echo Starting reverse ssh tunnel.

su -l -c "/usr/bin/autossh -4 -M29002 -f -N -R 1411:localhost:22 zjl@ -oLogLevel=error -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no" zjl || exit 0

#echo All done.

exit 0

nano /etc/network/if-up.d/stop_autossh_rev_tunnel



#echo Stopping any running autossh instances.

killall -q -TERM autossh

#echo All done.

exit 0

chmod +x /etc/network/if-up.d/stop_autossh_rev_tunnel  /etc/network/if-up.d/start_autossh_rev_tunnel


setting up ssh keys

reverse ssh tunnel

autossh script to start reverse tunnel

Ubuntu man page(s)

Leave a Reply

Your email address will not be published. Required fields are marked *