The what:
There are several cases when you just need some SSH tunnel to another system with some port redirections.
If the tunnel fails for whatever reason, it should reset itself. Setting up a SSH tunnel with port redirection as a service is the answer!
The How:
Creating SystemD config
The setup is a “user defined” config. When the user is logged on to the system, the service will become active.
You need to setup SSH password less login setup (with keys) to be able to use this.
First you need to created some directories (if not present)
mkdir -p ~/.config/systemd/user
Then create a SystemD service definition file inside this location
Name the file:
ssh_tunnel@.service
The content….:
# Author: VDV-IT Consultancy
# URL: https://www.vdv-it.nl
[Unit]
Description=Setup a secure tunnel to %I
After=network-online.target
[Service]
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes %i
# Restart every >2 seconds to avoid StartLimitInterval failure
RestartSec=5
Restart=always
[Install]
WantedBy=default.target
After creating the file, SystemD needs to know that this file is present. You need to do a reload of SystemD
systemctl --user daemon-reload
Almost done…..
Define the tunnels
To define a tunnel, add the following lines to your ~/.ssh/config file. If not present, create the file.
Host [Your tunnel name]
HostName [ip or url to remote computer]
Port [ssh port, usually 22]
User [username for login]
IdentityFile ~/.ssh/[the private key to be used].key
LocalForward [local port to listen] localhost:[remote port to connect to]
RemoteForward [remote port to listen] localhost:[local port to connect to]
More tunnels? just duplicate the block with other params.
If you need more option for SSH, take a look at man ssh_config
Running the tunnels
Lets get your hard work up and running!
Use the systemctl command to start/stop/status you’re tunnel
systemctl --user start ssh_tunnel@[your tunnel name]
To set-up autostart, use the same command but replace start with enable
This will start the tunnel when you log-on to your system.
systemctl --user enable ssh_tunnel@[your tunnel name]
Thats it! you’re up and running!
Checking / Stopping the tunnel
For status checking, use the systemctl command
systemctl --user status ssh_tunnel@[Your tunnel name]
To stop the tunnel
systemctl --user stop ssh_tunnel@[Your tunnel name]