21

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.

George Udosen
  • 37,534
ptf
  • 333

2 Answers2

32

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 cytopia@everythingcli.org -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

Pablo Bianchi
  • 17,371
George Udosen
  • 37,534
0

I added a -N to the command to get this to work. -N tells autossh to connect and do nothing. Without it my ssh session was logging in then immediately exiting. I also set it up to use a local user along with a .ssh/config file (/home/myuser/.ssh/config) which contains my tunnel rules.

# cat /etc/systemd/system/autossh.service
[Unit]
Description=AutoSSH service
After=network.target

[Service]
Environment="AUTOSSH_GATETIME=0"
User=myuser
Group=myuser
ExecStart=/usr/bin/autossh -N -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -i /home/myuser/.ssh/id_ecdsa_np remoteid@remote
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

Greenonline
  • 2,182
bonzo
  • 1