Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Systemd service for autossh
[Unit]
Description=Keeps a tunnel to 'remote.example.com' open
After=network.target
[Service]
User=autossh
# -p [PORT]
# -l [user]
# -M 0 --> no monitoring
# -N Just open the connection and do nothing (not interactive)
# LOCALPORT:IP_ON_EXAMPLE_COM:PORT_ON_EXAMPLE_COM
ExecStart=/usr/bin/autossh -M 0 -N -q -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -p 22 -l autossh remote.example.com -L 7474:127.0.0.1:7474 -i /home/autossh/.ssh/id_rsa
[Install]
WantedBy=multi-user.target
@mikkorantalainen
Copy link

mikkorantalainen commented Mar 22, 2023

For completeness, you should also add:

ExecStop=kill -9 autossh

Without it systemctl stop autossh won't do anything.

I think it would be better idea to add

KillMode=control-group

to the .service file because that will kill everything that was started (recursively) and nothing more. In addition, it will first send SIGTERM and use SIGKILL only if the process will not stop nicely.

If you randomly kill one or all autossh processes in the system, you might kill more than expected if autossh is used for other stuff, too.

See https://www.freedesktop.org/software/systemd/man/systemd.kill.html#KillMode= for details

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment