Skip to content

Instantly share code, notes, and snippets.

@MohamedElashri
Created September 28, 2024 22:14
Show Gist options
  • Save MohamedElashri/8cbb2ba8d04d6351a4ead02dcc258339 to your computer and use it in GitHub Desktop.
Save MohamedElashri/8cbb2ba8d04d6351a4ead02dcc258339 to your computer and use it in GitHub Desktop.
Persistent SSH Tunnel with systemd

This guide explains how to create a persistent SSH reverse tunnel using systemd without relying on tools like autossh. This approach automatically restarts the SSH tunnel if it fails or gets stuck due to disconnections.

Why Use systemd for SSH Tunnels?

Using systemd provides several benefits over standalone SSH or autossh:

  • Automatic Restart: If the SSH connection fails, systemd restarts it automatically.
  • Keep Alive: Prevents stale SSH connections by using SSH's ServerAliveInterval and ServerAliveCountMax.
  • Clean and Simple: Avoids external tools and manages the service with native system management.

Steps to Set Up

1. Install SSH

Ensure ssh is installed:

sudo apt install openssh-client

2. Create a systemd Service File

Create a service file in /etc/systemd/system/ssh-tunnel.service:

sudo nano /etc/systemd/system/ssh-tunnel.service

3. Add the Following Configuration

[Unit]
Description=Persistent SSH Tunnel
After=network.target

[Service]
Type=exec
ExecStart=/usr/bin/ssh -o ServerAliveInterval=60 -o ServerAliveCountMax=3 -o ExitOnForwardFailure=yes -Nn -R 7070:localhost:22 <remote_host> 'sleep 20m'
Restart=always
RestartSec=20
RuntimeMaxSec=30m

[Install]
WantedBy=default.target
  • ServerAliveInterval=60: Sends keep-alive packets every 60 seconds.
  • ServerAliveCountMax=3: Terminates the connection if 3 keep-alive packets are unanswered (180 seconds total).
  • ExitOnForwardFailure=yes: Ensures the service exits if port forwarding fails.

4. Start and Enable the Service

Start and enable the service so it runs at boot:

sudo systemctl start ssh-tunnel
sudo systemctl enable ssh-tunnel

5. Check Service Status

Verify the service is running:

sudo systemctl status ssh-tunnel

This configuration ensures a reliable reverse SSH tunnel that automatically reconnects after failure, preventing stale connections and minimizing manual intervention.

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