I use autossh to create a persistent tunnel from localhost to remotehost.

Starting autossh manually works fine, but if localhost reboots, the tunnel is gone. That's no surprise.

How to create a daemon to re-open around 20 tunnels after the reboot of localhost?

Server: Linux with systemd support


I found an systemd file to start an autossh daemon. In my case I would need create N such files:

Description=Keeps a tunnel to 'remote.example.com' open

# -p [PORT]
# -l [user]
# -M 0 --> no monitoring
# -N Just open the connection and do nothing (not interactive)
ExecStart=/usr/bin/autossh -M 0 -N -q -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -p 22 -l autossh remote.example.com -L 7474: -i /home/autossh/.ssh/id_rsa


Source: https://gist.github.com/thomasfr/9707568


Add whatever command you normally run to /etc/rc.local and put an & on the end if it.


We use monit to locally monitor/manage various processes on our servers. To manage autossh instances using monit, install the monit package and create a configuration file /etc/monit/conf.d/autossh.conf:

check process autossh1 pidfile "/tmp/autossh1.pid"
  start program = "/bin/bash -c 'export AUTOSSH_PIDFILE=/tmp/autossh1.pid; autossh -f user@host.example.com'" as uid user1 and group group1
  stop program = "/bin/bash -c 'kill `cat /tmp/autossh1.pid`'"
  group autossh

Then restart monit with sudo service monit restart.

If you want to run the process as root you can omit the as uid user1 and group group1 at the end of the start program = line.

monit will periodically check if the process is running and will restart it if needed. You can display the status of processes managed by monit:

monit summary

You can also easily stop/start the process by running

monit stop autossh1
monit start autossh1

You can even create groups (as illustrated by the line group autossh) and then stop/start whole groups:

monit stop -g autossh
monit start -g autossh

By the way, the monit command line tool uses HTTP to communicate with the daemon. To make the communication work you need to include the following in /etc/monit/monitrc:

set httpd port 2812 and
    use address localhost  # only accept connection from localhost
    allow localhost        # allow localhost to connect to the server

Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.