Since I am sharing the network without public IP, I would like to maintain a SSH tunnel so that I can connect to my desktop from the remote site. After searching the web, I found that Autossh fits my needs. Autossh is a utility that can start and monitor the SSH tunnel. If the connections are broken, then Autossh will restart the SSH connection automatically.
In this post, I would like to introduce how to setup an autossh daemon with Ubuntu Upstart.
Setup Local Host
First, create a new user:
# Create a new user named "autossh"
$ sudo adduser --system --group --disabled-password autossh
# Login as autossh
autossh:~$ sudo su autossh
Second, record the remote SSH server key:
autossh:~$ ssh-keyscan [remote] >> ~/.ssh/known_hosts
Third, create SSH public keys:
# Create SSH private and public keys
autossh:~$ ssh-keygen -t rsa
Enter file in which to save the key (/home/autossh/.ssh/id_rsa): [enter]
Created directory '/home/autossh/.ssh'.
Enter passphrase (empty for no passphrase): [enter]
Enter same passphrase again: [enter]
# Print the public key
autossh:~$ cat ~/.ssh/id_rsa.pub
[copy the output line]
Fourth, logout and disable the shell:
autossh:~$ exit
$ sudo chsh --shell /bin/false autossh
Setup Remote Host
First, create a new user:
# Login to the remote host
$ ssh [user]@[remote]
# Create a new user
remote:~$ sudo adduser --system --group --shell /bin/false \
--disabled-password autossh
Second, add the authorized public key:
# Create directory for authorized keys
remote:~$ sudo mkdir -p /home/autossh/.ssh
# Add new public key
remote:~$ sudo vi /home/autossh/.ssh/authorized_keys
[paste the public key]
# Change the owner of the file
remote:~$ sudo chown -R autossh:autossh /home/autossh/.ssh
We have finished the configuration on the remote host, logout from the remote host with:
remote:~$ exit
Setup Upstart Configuration File
(Update 2015/11/15: To setup a daemon for systemd, read this post instead.)
Let's add the Ubuntu Upstart configuration file.
First, create new upstart configuration with:
$ sudo vim /etc/init/autossh.conf
Add following lines to the file:
description "autossh daemon for ssh tunnel"
start on net-device-up IFACE=eth0
stop on runlevel [01S6]
setuid autossh
respawn
respawn limit 5 60
script
export AUTOSSH_FIRST_POLL=30
export AUTOSSH_GATETIME=0
export AUTOSSH_POLL=60
autossh -M [daemon-port] -N -R [remote-port]:localhost:22 [remote] -i /home/autossh/.ssh/id_rsa
end script
Change the variables properly.
[daemon-port]
can be any number larger than 8000.[remote-port]
is the remote port that will be opened on remote host which will be mapped to local port.- For the exported environment variables, you can refer to the autossh manual
pages for further details. Usually, you would like to set
AUTOSSH_GATETIME
to zero.
Finally, start the service now:
$ sudo service autossh start
After these steps, the SSH tunnel should start to work now!