Autossh Startup Script for Multiple Tunnels

When an encrypted VPN is not available, the next best solution is usually port-forwarding one or more port(s) through an SSH tunnel. The down-side of SSH is that by itself it cannot maintain a persistent connection — network issues may force the tunnel to stop responding, or even drop completely. Autossh is a small front-end for SSH that can monitor the connection, and restart the tunnel if it drops or stops responding. I found that the startup scripts available for autossh on the internet were a little too basic for my needs — I wanted autossh to start multiple connections, and to start/stop each one individually if I needed — so I wrote my own.

You’ll first need to install autossh — if you’re on an rpm-based distro, you can probably use yum install autossh.

The /etc/autossh/ directory contains the tunnel config file(s). You would typically have one configuration file per host. The filename can be whatever you like, but shorter filenames are probably best, since you can (optionally) use them on the command-line (for example /etc/init.d/autossh start dbhost1 dbhost2). If you don’t specify any filename(s) on the command-line, then all the config files are started, and all autossh processes are stopped.

Here’s an example host config file. You’ll have to make sure the LocalUser’s public SSH key has been added to the RemoteUser’s ~/.ssh/authorized_keys file., and you should try an su - {localuser} -c 'ssh -i {identityfile} -p {remoteport} {remoteuser}@{remotehost}' command first, before using the /etc/init.d/autossh script, just to make sure everything is working as it should. Remember that to listen on ports lower than 1024, either locally or remote, you will have to use root on that side.

The /etc/init.d/autossh script was written for CentOS, but should work fine — with little or no modifications — on most rpm-based distributions. You will probably want to add the script to your startup / shutdown process with a chkconfig --add autossh command, and you can view a short usage message by executing the script without any parameters.

You can download the autossh script here.