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.

Description=SSH Tunnel %i

# This whole mess is so the service won't start until WiFi is online. NetworkManager-wait-online.service NetworkManager-wait-online.service

ExecStart=/usr/bin/ssh -vCN %i


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
  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

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: November 4, 2020