Set up permanent SSH tunnel via cron

by Serban Simu
 

Description

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 to restart if necessary. On Unix systems this can be done via cron.

 

Instructions

Assume we want to tunnel local port 5000 to the remote computer 10.0.109.1 port 6000.

1. Make sure SSH works - choose a user with an SSH private key such that the ssh command doesn't require a password. Make sure you're not asked for password when connecting. Exit once it connects correctly:

ssh root@10.0.109.1

 

2. Test the tunnel manually. The following command should open a tunnel and background the ssh process:

nc -z localhost 5000 || ssh -N -L 5000:10.0.109.1:6000 root@10.0.109.1 &

 

To terminate it, type fg and then Ctrl-C.

3. Edit crontab and add the command above. For example, to 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 &
Have more questions? Submit a request

0 Comments

Article is closed for comments.
Powered by Zendesk