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.

18 thoughts on “Autossh Startup Script for Multiple Tunnels

  1. Thk for the script.

    After some search I believe that a better use of ssh config file is a good way to do the same with a lot of param stored into ssh_config file
    For instance into my config file I can store the following :

    Host *
    ServerAliveInterval 10
    ServerAliveCountMax 3
    StrictHostKeyChecking no

    Host db1
    IdentityFile ~/.ssh/
    Port 22
    User dbuser
    RemoteForward 3307
    LocalForward 8081

    And outside (into your config file) we need only TWO things :


    I try to adapt your script following that ;)

  2. Hi there Jean-Sebastien

    I just want to compliment you on the quality of your scripting and say an especially big thanks for letting others take advantage of your hard work.

    By way of expressing my appreciation I am pasting an updated version with a few minor changes that I hope you find useful.

    The changes are as follows:

    1. A new “AutoStart” variable with legal values “yes” and “no”. “no” means that the tunnel will not start when the command is run “in general start mode” ie. “/etc/init.d/autossh start”. “yes” on the other hand means that the tunnel will start. To start a tunnel with a value of “no” the “/etc/init.d/autossh start TunnelName” format must be used. The idea is that this will be useful for cherry picking tunnels to auto-start at server boot, as opposed to those started manually when desired.
    2. A utility function to automatically generate a full configuration file with examples in the configuration folder if it doesn’t exist – “autossh.config.example”. This example configuration file is entirely ignored by the executable when starting and stopping tunnels.
    3. A “privileged port check” which checks for ports 1024 and less and if found checks that the LocalUser is root
    4. I have also made a few minor changes to the command syntax.

    This script has been tested working on CentOS 6.4 but I can’t speak for other OSs.

    The updated script follows here:

    # autossh . Startup script for autossh

    # chkconfig: 2345 25 40
    # description: Maintain persistent SSH tunnels
    # processname: autossh
    # pidfile: /var/run/

    # Copyright 2012 – Jean-Sebastien Morisset –
    # 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

    # Changelog:
    # 2013/06/21 – Reset the $forward_list variable at the start() to prevent the
    # accumulation of ports for each config loop. Also added support for socks
    # proxies. Thanks to Chris for pointing out the issue in the comments.

    # Constants

    # Variables

    # Functions

    # Source function library
    . /etc/init.d/functions

    # creates and populates an example configuration file if it doesn’t already exist
    # (also creates the configuration file directory if it doesn’t exist)
    function createExampleConfigFile() {
    if [ ! -f ${exampleConfigFile} ]; then
    if [ ! -d ${configPath} ]; then
    mkdir -p ${configPath}
    if [ $? -gt 0 ]; then
    doFail “Could not create configuration path \”${configPath}\””
    chown root:root ${configPath}
    chmod o-a ${configPath}
    echo \
    # The example configuration file
    # NOTES:
    # 1. This file will not be processed by the startup script
    # It is recommended to leave this file as-is and create new configuration
    # files as necessary for your purposes.
    # 2. Configuration files can be called whatever you like but short meaningful
    # names are recommended. eg. A tunnel to ThisCompanyServer might have a file
    # called “Company” or “ThisCompanyServer” or even “TCS”
    # The general recommendation is to keep the name short, easy to remember
    # and meaningful
    # Typical steps for creating new tunnel are as follows…
    # 1. Create a configuration file for your tunnel in this directory
    # 2. Make sure that the LocalUser selected in the configuration file exists on this
    # server and has an RSA certificate created for it.
    # NOTE: when creating the certificate it MUST be created by the selected
    # LocalUser, otherwise it will not work
    # 3. Make sure that the selected RemoteUser exists on the remote server
    # and that LocalUser public key has been inserted into RemoteUser
    # authorized_keys file (explained further below)
    # 4. Test by su – LocalUser then ssh -oPort=RemotePort RemoteUser@RemoteHost
    # and make sure the ssh logs in successfull without asking for the RemoteUser
    # password. For debugging try including -vvv switch in the ssh command.
    # 5. When testing successful, start your new “Company” tunnel using:
    # /etc/init.d/autossh start Company
    # Do not forget to append your new tunnel configuration file otherwise
    # if only start is used all tunnels will be started
    # For full command usage explanation type: /etc/init.d/autossh

    # Please replace the text here with a brief description of the tunnel purpose
    # for others to reference in future
    # NOTE: comments are prefixed by “#”. This explanation is a comment so
    # please make sure it is prefixed appropriately

    # Example values follow from here

    # If this value is set to “yes” it will autostart when the command is run
    # without specifying the configuration file name. ie /etc/init.d/autossh start
    # “start all” may of course happen manually but would typically occur at server boot
    # setting the value to “anything else” ie. no means that the tunnel will only
    # start when explicitly run ie. /etc/init.d/autossh start

    # Check connection every 10 seconds, and after 3 tries (30 seconds), drop and
    # let autossh re-connect.

    # the user on the local machine that will be used to create the tunnel

    # the id file that will be used to identify the user to the remote machine user
    # the public key of this user ~/.ssh/ contents must be inserted into
    # the chosen RemoteUser ~/.ssh/authorized_keys file on the remote server

    # the remote user with whom the tunnel will be established.
    # this user must exist on the remote machine and must have the public key
    # of LocalUser as explained above

    # The fully qualified host name or IP address of the remote host with which
    # the tunnel is to be established

    # The port on the remote server with which the tunnel is to be established
    # This port must be active and accessible through the remote server
    # firewall (if enabled)

    # Array of ports to be forwarded:


    “R localhost:3307:localhost:3306” # Forward port 3307, listening on on the remote side, to port 3306 on the local side.
    “L *:1234:localhost:8888” # Forward port 1234, listening on all local side interfaces to the localhost port 8888 on the remote side.
    “L localhost:8081:” # Forward port 8081, listening on on the local side, to port 80 on the remote side.
    “D localhost:6767” # (NOTE!! not tested as yet)SOCKS proxy all local ports to port 6767 on the remote side.

    )’ > ${exampleConfigFile}
    chown root:root ${exampleConfigFile}
    chmod o-r ${exampleConfigFile}


    function doFail() {
    echo “$prog $cfname: $1”
    exit 1

    function awkTest() {
    local expression=$1
    if awk “BEGIN {exit ${expression} ? 0 : 1}”; then
    echo true
    echo false

    function checkPortOK() {
    local portToCheck=$1
    if [ $(awkTest “${portToCheck} <= ${cMaxPrivilegedPort}") = true -a "${LocalUser}" != "root" ]; then
    doFail "\"$fwd\" – Port ${portToCheck} is privileged (less than $(expr ${cMaxPrivilegedPort} + 1)), so LocalUser must be 'root' for it to work (currently ${LocalUser})"

    [ ! -d /var/run/$prog ] && mkdir -p /var/run/$prog

    start() {
    cfname=basename $config

    # make sure the example configuration file exists

    # make sure we have a config file
    if [ ! -f "$config" ]
    doFail "$config missing"

    . $config

    # make sure all variables have been defined in config
    for var in \
    ServerAliveInterval ServerAliveCountMax StrictHostKeyChecking \
    LocalUser IdentityFile RemoteUser RemoteHost RemotePort AutoStart
    do eval "
    if [ -z \$$var ]
    doFail \"$var variable empty\"

    if [ ${#ForwardPort[*]} -eq 0 ]
    doFail "ForwardPort array empty"

    for fwd in "${ForwardPort[@]}"
    case "$fwd" in
    D\ *:*|R\ *:*:*:*|L\ *:*:*:*)
    checkPortOK "$(echo $fwd | cut -f2 -d:)"
    forward_list+="-$fwd " ;;
    doFail "$fwd format unknown"

    # define the pidfile variable for autossh (created by autossh)
    # check if pidfile already exists — don't start another instance if pidfile exists
    if [ -e $AUTOSSH_PIDFILE ]
    doFail "$AUTOSSH_PIDFILE already exists"

    # if this is a "start all" call and the tunnel is not configured to auto start
    if [ ! "${allBoo}" = "no" -a ! "${AutoStart}" = "yes" ]; then #
    echo "$prog $cfname: Tunnel not configured to auto start. Ignoring…"
    return 0 # we return to the caller without starting the tunnel

    # we are about to begin starting the tunnel….

    echo -n "Starting $prog $cfname: "

    # before switching-users, make sure pidfile is created and user has write permission
    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 -s /bin/sh – $LocalUser -c "
    $autossh -M 0 -f -gNC \
    -i $IdentityFile \
    -o \"Port $RemotePort\" \
    -o \"ServerAliveInterval $ServerAliveInterval\" \
    -o \"ServerAliveCountMax $ServerAliveCountMax\" \
    -o \"StrictHostKeyChecking $StrictHostKeyChecking\" \
    $forward_list $RemoteUser@$RemoteHost;"

    # check to make sure pidfile was created
    if [ ! -f $AUTOSSH_PIDFILE ]
    doFail "basename $AUTOSSH_PIDFILE not created"

    touch /var/lock/subsys/$prog

    stop() {
    # if no config names (on the command-line), stop all autossh processes
    if [ -z "$config" ]
    echo -n "Stopping all $prog: "
    killproc $autossh
    if [ $RETVAL -eq 0 ]
    rm -f /var/lock/subsys/$prog
    rm -f /var/run/$prog/*.pid
    cfname="basename $config"
    if [ ! -f $pidfile ]
    doFail "$pidfile missing"
    echo -n $"Stopping $prog $cfname: "
    killproc -p "/var/run/$prog/$" "$prog $cfname"
    [ $RETVAL -eq 0 ] && rm -f /var/run/$prog/$
    return $RETVAL

    # save the action name, and shift the command-line array
    # all remaining command-line arguments could be config names

    case "$action" in
    if [ -z "$1" ]; then
    # if no config names on the command-line, start all /etc/autossh/ configs found
    for config in $(echo ${configPath}/${cfname:='*'}); do
    if [ "${config}" != "${exampleConfigFile}" ]; then # here we ensure we ignore the dummy example configuration file
    $action "${config}" "yes";
    # start only the config files specified on the command-line
    for cfname in "$@"; do
    $action "${configPath}/${cfname}" "no"
    if [ -z "$1" ]
    # if no config names on the command-line, stop all autossh processes
    # stop only the config files specified on the command-line
    for cfname in "$@"
    do $action ${configPath}/$cfname; done
    # re-execute this script, with the stop and start action names instead
    $0 stop "$@"
    $0 start "$@"
    if [ -z "$1" ]
    # if no config names on the command-line, show all autossh pids
    status $autossh
    # only show the status of config files specified on the command-line
    for cfname in "$@"
    # if the config file is missing, echo an error message
    if [ -f $config ]
    cfname="basename $config"
    # if the pidfile is missing, echo an error message
    if [ -f $pidfile ]
    status -p "$pidfile" "$prog $cfname"
    echo "$pidfile missing"
    echo "$config missing"
    echo "Usage: $0 {start|stop|restart|status} {config names…}"
    exit $RETVAL

  3. Hi,

    thank you for that script. Which is the intended distribution?
    Ive tried Debian, but I think there are several changes necessary.

    The Shebang is /bin/sh – but there are arrays used. So I think /bin/bash is the right one. But there are some more changes needed (eg lockfile) for Debian.
    Best regards

    • Rudolf,

      As the post mentions, “The /etc/init.d/autossh script was written for CentOS, but should work fine — with little or no modifications — on most rpm-based distributions.”

      /bin/sh on Linux has traditionally been a symlink to /bin/bash. I’ve modified the script to use /bin/bash to avoid any confusion.



  4. One of the WordPress security plugins I’m using filters for user agents, among many other things, which is why you got a 403 (forbidden) on that file. There’s no reason to limit wget, so I’ve bypassed that configuration rule. You should be able to wget the file now. ;-)

    Thanks for letting me know.


  5. First, this saves me significant work, thank you!

    Two things I’ll be looking to add, unless you want to first:

    1.Read the configuration file from /etc/sysconfig/autossh like other CentOS startup scripts. It could still take the command line parameter, but if not specified, look for the sysconfig file first before exiting.

    2. add support for the common –help to display the usage mesasge.

  6. Hi,

    I have the same problem as others on this posting and am hoping you can identify the problem.

    I use autossh to maintain multiple (50+) tunnels and whilst I can start all 50 individually or from a single command line without any problem, if I do not specify a config file then the port forwards from all files are loaded into the array and added to every connection.

    I’m no bash expert but think the problem may be here:

    D\ *:*|R\ *:*:*:*|L\ *:*:*:*) forward_list+=”-$fwd ” ;;

    (I added D\ *:*| to allow use of socks proxies in the config)

    I need both port forwarding and socks proxying so could you let me know if there is a way to isolate the forwards based on a config file when no config file is used in the start-up syntax?

    Thanks for the great work.

    Best regards


  7. 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.

  8. 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?


    • 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.


      • 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!

  9. 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.

  10. Instead of individually configuring ports, you could create a SOCKS proxy on port 1080 (for instance) by using ssh’s D option like this:

    […] -D 1080 RemoteUser@RemoteHost

    which gives you automatic port forwarding.

    In some circumstances, this may be better than individual port forwarding configuration.

Comments are closed.