Automatically restart SSH sessions and tunnels Using Autossh

Sponsored Link
autossh is a program to start a copy of ssh and monitor it, restarting it as necessary should it die or stop passing traffic.The original idea and the mechanism were from rstunnel (Reliable SSH Tunnel). With version 1.2 of autossh the method changed: autossh uses ssh to construct a loop of ssh forwardings (one from local to remote, one from remote to local), and then sends test data that it expects to get back.

With version 1.3, a new method is added (thanks to Ron Yorston): a port may be specified for a remote echo service that will echo back the test data. This avoids the congestion and the aggravation of making sure all the port numbers on the remote machine do not collide. The loop-of-forwardings method remains available for situations where using an echo service may not be possible.

Install autossh in ubuntu

Open the terminal and run the following command

sudo apt-get install autossh

Autossh syntax

autossh [-V] [-M port[:echo_port]] [-f] [SSH_OPTIONS]

Start ssh tunnel at boot time

We can use upstart to start ssh tunnel under Ubuntu by put the following autossh.conf file under /etc/init/ folder

# autossh startup Script

description "autossh daemon startup"

start on net-device-up IFACE=eth0
stop on runlevel [01S6]

respawn limit 5 60 # respawn max 5 times in 60 seconds

export AUTOSSH_PIDFILE=/var/run/
export AUTOSSH_POLL=60
autossh -M 0 -4 -N USER@HOSTNAME -D 7070 -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -o BatchMode=yes -o StrictHostKeyChecking=no -i SSH_KEY_FILE_PATH
end script

Sponsored Link

Related posts

2 thoughts on “Automatically restart SSH sessions and tunnels Using Autossh

  1. Hi,

    thanks for this post.

    How would a standard init.d script for the same job look like?


  2. You can also add the autossh command in crontab with @reboot attribute so that it runs everytime server is rebooted.

Leave a comment

Your email address will not be published. Required fields are marked *