Set up permanent ssh tunnel via cron

From MyWiki
Jump to: navigation, search
Set up permanent SSH tunnel via cron
 
Devenie Corliss
posted this on May 25, 2011, 17:40
by Serban Simu
 
SSH tunnels are very useful when deploying applications in distributed environments. They are easy to set up manually, but often we need a permanent SSH tunnel, to start automatically when the system starts up and restart if necessary. On Unix systems this can be done via "cron".
 
Assume we want to tunnel local port 5000 to the remote computer 10.0.109.1 port 6000.
 
Make sure SSH works - choose a user with an SSH private key such that the ssh command doesn't require a password
ssh root@10.0.109.1
(make sure it doesn't ask for password; exit once it connects correctly)
 
Test the tunnel manually:
nc -z localhost 5000 || ssh -N -L 5000:10.0.109.1:6000 root@10.0.109.1 &
This should open a tunnel and background the ssh process. To terminate it, type fg and thenCtrl-C.
 
Edit crontab and add the command above. For example run it every minute, as user root
crontab -u root -e
And add at the end of it:
 
* * * * * nc -z localhost 5000 || ssh -N -L 5000:10.0.109.1:6000 root@10.0.109.1 &
0 people found this useful. - Be the first!
 
==============================
 
below sets up connection from server to client
*/5 * * * * /root/wget.sh > /dev/null 2>&1
*/5 * * * * /usr/bin/ssh -l root own.twig.tk nc -z localhost 8080 || ssh -N -l root own.twig.tk -R *:8080:localhost:8080 &
root@raspberrypi:~#