4

Can anyone point me in the direction of a good (step by step) resource for setting up a reverse ssh tunnel with autossh using systemd at boot?

I've tried my best to do this using resources I've found online and have succeeded in manually creating the reverse ssh session, however haven't managed to automate it with systemd such that my "remote" system can reboot without causing issues.

I'm trying to establish a persistent autossh session using this tutorial, however when I run sudo systemctl enable autossh.service I keep running into this error: update-rc.d: error: cannot find a LSB script for autossh.

Any help deciphering this error or creating a persistent autossh session on Ubuntu 20.04 would be greatly appreciated.

autossh.service file:

[Unit]
Description=Establish persistent SSH tunnel
Requires=ssh.service
Wants=network-online.target
After=network-online.target

[Service]
User=user
Group=usergroup
Environment=AUTOSSH_POLL=60 AUTOSSH_FIRST_POLL=30 AUTOSSH_LOGFILE=/var/log/autossh.log AUTOSSH_LOGLEVEL=7 AUTOSSH_GATETIME=0
ExecStart=/usr/bin/autossh -i /root/.ssh/id_rsa -R 3010:localhost:22 -o 'StrictHostKeyChecking=no' -o 'UserKnownHostsFile=/dev/null' -o 'PasswordAuthentication=no' -o 'PubkeyAuthentication=yes' -o 'ServerAliveInterval 60' -o 'ServerAliveCountMax 3' -o 'BatchMode=yes' user@myddnsservice -p2016
RestartSec=6
Restart=always

[Install]
WantedBy=multi-user.target

1 Answer 1

8

This is what I use.

Create the tunnel private/public key using ssh-keygen on the remote machine. You will be prompted for a passphrase. You can press Enter to ignore the passphrase questions, but this is not recommended. It would mean that anyone on the remote computer could make an SSH connection to your local computer without being challenged for a password (see the "Using SSH With Keys" section).

Install the public key in your remote [email protected] .ssh/authorized_keys file

Test it by manually trying the ssh command and make sure the reverse tunnel is working.

vi /etc/systemd/system/tunnel.service

[Unit]
Description=Maintain Tunnel
After=network.target

[Service]
User=localuser
ExecStart=/usr/bin/ssh -i ~localuser/.ssh/tunnel -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -gnNT -R 22222:localhost:22 remoteuser@remotehost vmstat 5
RestartSec=15
Restart=always
KillMode=mixed

[Install]
WantedBy=multi-user.target

Then run:

sudo systemctl daemon-reload
sudo systemctl enable tunnel
sudo systemctl start tunnel
2
  • 2
    Worked like a charm! Thanks very much for your help Simon! Feb 16, 2021 at 11:57
  • 1
    Great to have a simple template to follow. Adjusted it a tiny bit to use autossh instead of normal ssh to get more stable connections. My service file also contains a bunch of tips for debugging when this does not work as expected: github.com/fatso83/dotfiles/commit/…
    – oligofren
    Oct 27, 2021 at 14:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .