HOW TO: Create ssh tunnel at boot time under Ubuntu

Create ssh tunnel

The simplest command to create a ssh tunnel is:

#The following command will create a sock5 proxy on port 7070, and then you can use it in your browser
ssh -ND 7070 HOSTNAME

Use Autossh instead of ssh

I prefer to use autossh instead of ssh because it will auto reconnect if the connection lost, here’s the description from it’s homepage:

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 idea is from rstunnel (Reliable SSH Tunnel), but implemented in C

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

description "autossh daemon"

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
    export AUTOSSH_FIRST_POLL=30
    export AUTOSSH_DEBUG=1
    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

2 thoughts on “HOW TO: Create ssh tunnel at boot time under Ubuntu”

Leave a Reply

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