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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Check connection every 10 seconds, and after 3 tries (30 seconds), drop and # let autossh re-connect. ServerAliveInterval="10" ServerAliveCountMax="3" StrictHostKeyChecking="no" LocalUser="root" IdentityFile="~/.ssh/domain.com" RemoteUser="dbuser" RemoteHost="db1.domain.com" RemotePort="22" # Array of ports to be forwarded: # # Example: Forward port 3307, listening on 127.0.0.1 on the remote side, to # 127.0.0.1 port 3306 on the local side. Forward port 8081, listening on # 127.0.0.1 on the local side, to 10.100.1.60 port 80 on the remote side. # ForwardPort=( "R 127.0.0.1:3307:127.0.0.1:3306" "L 127.0.0.1:8081:10.100.1.60:80" ) |
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.
|
1 2 |
$ /etc/init.d/autossh Usage: /etc/init.d/autossh {start|stop|restart|status} {config names...} |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
#!/bin/sh # # autossh . Startup script for autossh # chkconfig: 2345 25 40 # description: Maintain persistent SSH tunnels # processname: autossh # pidfile: /var/run/autossh.pid # Copyright 2012 - Jean-Sebastien Morisset - http://surniaulula.com/ # # This script is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; either version 3 of the License, or (at your option) any later # version. # # This script is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details at http://www.gnu.org/licenses/. # Source function library . /etc/init.d/functions RETVAL=0 prog="autossh" autossh="/usr/bin/autossh" [ ! -d /var/run/$prog ] && mkdir -p /var/run/$prog start() { config="$1" cfname=`basename $config` # make sure we have a config file if [ ! -f "$config" ] then failure echo "$prog $cfname: $config missing" return 1 fi . $config # make sure all variables have been defined in config for var in \ ServerAliveInterval ServerAliveCountMax StrictHostKeyChecking \ LocalUser IdentityFile RemoteUser RemoteHost RemotePort do eval " if [ -z \$$var ] then failure echo \"$prog $cfname: $var variable empty\" return 1 fi " done if [ ${#ForwardPort[*]} -eq 0 ] then failure echo "$prog $cfname: ForwardPort array empty" return 1 fi for fwd in "${ForwardPort[@]}" do case "$fwd" in R\ *:*:*:*|L\ *:*:*:*) forward_list+="-$fwd " ;; *) failure echo "$prog $cfname: $fwd format unknown" return 1 ;; esac done # define the pidfile variable for autossh (created by autossh) # check if pidfile already exists -- don't start another instance if pidfile exists AUTOSSH_PIDFILE="/var/run/$prog/$cfname.pid" if [ -e $AUTOSSH_PIDFILE ] then failure echo "$prog $cfname: $AUTOSSH_PIDFILE already exists" return 1 fi echo -n "Starting $prog $cfname: " # before switching-users, make sure pidfile is created and user has write permission touch $AUTOSSH_PIDFILE chown $LocalUser $AUTOSSH_PIDFILE # start autossh as the user defined in the config file # the pidfile must be re-defined in the new environment su - $LocalUser -c " AUTOSSH_PIDFILE=$AUTOSSH_PIDFILE; AUTOSSH_PORT=0; export AUTOSSH_PIDFILE AUTOSSH_PORT; $autossh -q -N -p $RemotePort \ -i $IdentityFile \ -o ServerAliveInterval=$ServerAliveInterval \ -o ServerAliveCountMax=$ServerAliveCountMax \ -o StrictHostKeyChecking=$StrictHostKeyChecking \ $forward_list $RemoteUser@$RemoteHost -f;" # check to make sure pidfile was created if [ ! -f $AUTOSSH_PIDFILE ] then failure echo "`basename $AUTOSSH_PIDFILE` not created" return 1 fi success echo touch /var/lock/subsys/$prog } stop() { config="$1" # if no config names (on the command-line), stop all autossh processes if [ -z "$config" ] then echo -n "Stopping all $prog: " killproc $autossh RETVAL=$? echo if [ $RETVAL -eq 0 ] then rm -f /var/lock/subsys/$prog rm -f /var/run/$prog/*.pid fi else cfname="`basename $config`" pidfile="/var/run/$prog/$cfname.pid" if [ ! -f $pidfile ] then failure echo "$prog $cfname: $pidfile missing" return 1 else echo -n $"Stopping $prog $cfname: " killproc -p "/var/run/$prog/$cfname.pid" "$prog $cfname" RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f /var/run/$prog/$cfname.pid fi fi return $RETVAL } # save the action name, and shift the command-line array # all remaining command-line arguments could be config names action="$1" shift case "$action" in start) if [ -z "$1" ] then # if no config names on the command-line, start all /etc/autossh/ configs found for config in `echo /etc/$prog/${cfname:='*'}` do $action $config; done else # start only the config files specified on the command-line for cfname in "$@" do $action /etc/$prog/$cfname; done fi ;; stop) if [ -z "$1" ] then # if no config names on the command-line, stop all autossh processes $action else # stop only the config files specified on the command-line for cfname in "$@" do $action /etc/$prog/$cfname; done fi ;; restart) # re-execute this script, with the stop and start action names instead $0 stop "$@" $0 start "$@" ;; status) if [ -z "$1" ] then # if no config names on the command-line, show all autossh pids status $autossh RETVAL=$? else # only show the status of config files specified on the command-line for cfname in "$@" do config="/etc/$prog/$cfname" # if the config file is missing, echo an error message if [ -f $config ] then cfname="`basename $config`" pidfile="/var/run/$prog/$cfname.pid" # if the pidfile is missing, echo an error message if [ -f $pidfile ] then status -p "$pidfile" "$prog $cfname" RETVAL=$? else echo "$pidfile missing" RETVAL=1 fi else echo "$config missing" RETVAL=1 fi done fi ;; *) echo "Usage: $0 {start|stop|restart|status} {config names...}" RETVAL=1 ;; esac exit $RETVAL |
You can download the autossh script here.
Did you find this post useful? Share it with your circles / friends, or leave a quick note bellow.
Thank you,
js.

Hi,
I have the problem. Basically, I had 2 tunnels with different key file. Sometime I want to start with 2 tunnels at the same with this – /etc/init.d/autossh start, the tunnel was created with the wrong PortForward. For e.g., the tunnel 1 use Local PortForward of tunnel 2 which will not work. This made me to start them separately – /etc/init.d/autossh start config tunnel1 & /etc/init.d/autossh start config tunnel2. Is there anyway that I can start multiple tunnels at the same time. Thank you.
Hi Jean,
First of all, many thanks for this tutorial…Simply wonderful.
Bu ti have a slight issue, I want to go beyond 2 tunnels ( I need like 5 tunnels for the project am working on), but any time i create and test the 3rd tunnel ( i have only successfully created 2 tunnels), it gives the following error: “Connection closed by remote host”
Output of SSH debugging:
Please is there any consideration when you are creating more than 2 tunnels at the same time?
Thanks
Provided you are not trying to redirect a low port (less than 1024), you should be able to redirect any number of ports. To redirect low port(s), you have to be a privileged user (like root).
Your output shows an error with the /var/log/nagios/.ssh/id_rsa key, so you might want to look at that.
BTW, I see you are connecting back to localhost. Don’t forget that you can’t redirect a port back onto itself on the same server / IP — to do that you’ll need different source and destination port numbers.
js.
Many thanks Jean!
Am actually using the project to implement some Nagios checks via SSH (Currently don’t have the luxury of SNMP or NRPE). So I want to use autossh to create the SSH tunnels which I will reference in my Custom Plugins.
Please can you explain this a little bit, probably an example command :
“BTW, I see you are connecting back to localhost. Don’t forget that you can’t redirect a port back onto itself on the same server / IP — to do that you’ll need different source and destination port numbers.”
Many thanks Bro!
Thanks for posting this. For my purpose I only need a single user but this gives me all that I need to move forward with my project. This was very helpful. I didn’t find anything this comprehensive anywhere else.
[...] comment below main article – The Daily Build) SSH Socks proxy with Chromium 18 (krenel.org) Autossh Startup Script for Multiple Tunnels (Surnia [...]
Great stuff !! Just used it for one of my crazy projects :) Thank you for spending the time and sharing it !!