Start autossh on system startup

Is there any way to start autossh on startup, so that it starts and sets up the ssh tunnel before a user has even logged in? I boot Ubuntu to terminal, and I'd like that the autossh process starts automatically on startup so I can ssh in.

I've tried adding the command to /etc/rc.local, as well as to create a /etc/init/*.conf script. None of these seems to work.


Solution 1:

Using systemd this can be done (sample autossh created for mysql access):

  1. Create a systemd file using nano or vim or appropriate editor of choice:

    sudo vim /etc/systemd/system/autossh-mysql-tunnel.service 
    
  2. Add the following contents:

    [Unit]
    Description=AutoSSH tunnel service everythingcli MySQL on local port 5000
    After=network.target
    
    [Service]
    Environment="AUTOSSH_GATETIME=0"
    ExecStart=/usr/bin/autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -NL 5000:localhost:3306 [email protected] -p 1022
    
    [Install]
    WantedBy=multi-user.target
    
  3. Reload systemd:

    sudo systemctl daemon-reload
    
  4. Start the Autossh service:

    sudo systemctl start autossh-mysql-tunnel.service
    
  5. Enable at boot:

    sudo systemctl enable autossh-mysql-tunnel.service
    
  6. Check status with:

    sudo systemctl status autossh-mysql-tunnel
    

Note

There is however an important thing to note about systemd and AutoSSH: -f (background usage) already implies AUTOSSH_GATETIME=0, however -f is not supported by systemd.

So in the case of systemd you need to make use of AUTOSSH_GATETIME

Source

  • https://www.everythingcli.org/ssh-tunnelling-for-fun-and-profit-autossh/
  • https://www.freedesktop.org/software/systemd/man/systemd.service.html