Skip to content

SSH tunnel with Systemd service

This is a service unit I use to setup my ssh tunnels. Save it under $HOME/.config/systemd/user/autossh@.service for example.

[Unit]
Description=SSH Tunnel %i

# This whole mess is so the service won't start until WiFi is online.
Wants=network-online.target NetworkManager-wait-online.service
After=network.target network-online.target NetworkManager-wait-online.service

[Service]
Type=simple
ExecStart=/usr/bin/ssh -vCN %i
KillMode=process
Restart=always
RestartSec=5
SyslogIdentifier=autossh@%i

[Install]
WantedBy=multi-user.target

That way I can restart a specific tunnel like systemctl --user restart autossh@my-tunnel.

And since it runs as my user the ssh config is the normal one under $HOME/.ssh.

Host my-tunnel
  HostName 10.0.0.1
  User my-user
  DynamicForward localhost:56443

You can also enable it and start it at the same time.

$ systemd --user enable --now autossh@my-tunnel

Shortly about systemd dependencies

I don't know of a way to write dependencies between the tunnels but it doesn't matter much because the tunnels I have that depend on other tunnels will restart every 5 seconds until they're live.

To figure out your dependencies in After and Wants you can run this command.

$ systemctl is-enabled NetworkManager-wait-online.service systemd-networkd-wait-online.service
enabled
disabled

Only one of those should be enabled, that's the one you should use as a dependency. I've input both to be on the safe side.


Last update: July 3, 2020