Tech/Cooking comfy SSH tunnels

From ~esantoro

As I wrote in Blog/Software tools I like (Jan 2025) a nice tool i use often is boring (an ssh tunnel manager).

Somehow, today i found out it broke. I let the original author know and started looking for something else to use in the meantime.

Alternatives were not looking so promised so i looked into cooking up something of my own, and here is the result.

Long story short, I go back to good old ssh -TL localport:remotehost:remoteport ssh_user@ssh_host BUT i let systemd manage all the annoyances for me.

This is my beautiful systemd unit I placed in ~/ssh-tunnel@.service

[Unit]
Description=SSH tunnel (%i)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple

# Load per-instance environment vars
EnvironmentFile=%h/.config/ssh-tunnel-%i.env

# The SSH tunnel
ExecStart=/usr/bin/ssh -N -T \
    -o ExitOnForwardFailure=yes \
    -o ServerAliveInterval=30 \
    -o ServerAliveCountMax=3 \
    -L ${LOCAL_PORT}:${REMOTE_ADDR}:${REMOTE_PORT} \
    ${REMOTE_USER}@${REMOTE_HOST}

# Auto-restart on failure
Restart=always
RestartSec=5

# Optional: if using keys with passphrases, ssh-agent etc.
# Environment=SSH_AUTH_SOCK=%h/.ssh/ssh_auth_sock

[Install]
WantedBy=default.target

The nice thing is that I can create environment files at /home/<my-user>/.config/ssh-tunnel-<instance>.env As an example,here is one:

LOCAL_PORT=8006
REMOTE_ADDR=192.168.52.73
REMOTE_PORT=8006
REMOTE_USER=root
REMOTE_HOST=10.250.0.12

# Optional: extra SSH options
SSH_OPTS="-i /home/esantoro/.ssh/id_ecdsa

Enabling the unit is fairly simple:

systemctl --user enable --now ssh-tunnel@pvek.service

As well as start and stopping:

# starting:
systemctl --user start ssh-tunnel@pvek.service

# stopping
systemctl --user stop ssh-tunnel@pvek.service

As well as "giving it a look":

esantoro@x13:~$ systemctl --user status ssh-tunnel@pvek.service
● ssh-tunnel@pvek.service - SSH tunnel (pvek)
     Loaded: loaded (/home/esantoro/.config/systemd/user/ssh-tunnel@.service; enabled; preset: disabled)
    Drop-In: /usr/lib/systemd/user/service.d
             └─10-timeout-abort.conf
     Active: active (running) since Sat 2025-12-06 01:13:47 CET; 10min ago
 Invocation: 39acc541341c448e9c28126ddd09237f
   Main PID: 20827 (ssh)
      Tasks: 1 (limit: 37377)
     Memory: 2.7M (peak: 3.4M)
        CPU: 112ms
     CGroup: /user.slice/user-1000.slice/user@1000.service/app.slice/app-ssh\x2dtunnel.slice/ssh-tunnel@pvek.service
             └─20827 /usr/bin/ssh -N -T -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -L 8006:192.168.52.73:8006 root@10.250.0.12

Dec 06 01:13:47 x13 systemd[2651]: Started ssh-tunnel@pvek.service - SSH tunnel (pvek).
esantoro@x13:~$

Too bad there's no systemd in mac os (I have a macbook from work).