Set up permanent SSH tunnel via cron

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



Assume we want to tunnel local port 5000 to the remote computer 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@


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: root@ &


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: root@ &
Have more questions? Submit a request


Article is closed for comments.
Powered by Zendesk