Secure Shell (SSH) tunnels provide a secure way to forward traffic from one machine to another. This can be extremely useful for accessing services behind firewalls, securing database connections, or simply accessing remote systems securely. However, keeping an SSH tunnel open and reconnecting it in case of a failure can be cumbersome. This is where systemd comes in. By leveraging systemd, you can create a persistent SSH tunnel that automatically restarts if it goes down. Here’s how you can do it.
Create a Systemd Service File
Create a new service file for the SSH tunnel. Open a new file in /etc/systemd/system/ with a descriptive name, such as sshtunnel.service:
sudo nano /etc/systemd/system/sshtunnel.service
Add the following content to the file:
[Unit]
Description=SSH Tunnel
After=network.target[Service]
User=root
ExecStart=/usr/bin/ssh -i /path/to/your_private_key -N -L *:local_port:localhost:remote_port username@remote_host
Restart=always
RestartSec=5s
StartLimitInterval=0[Install]
WantedBy=multi-user.target
Replace the following placeholders:
/path/to/your_private_key
: The full path to your private SSH key.local_port
: The local port you want to use.remote_port
: The remote port you want to connect to.username
: Your username on the remote server.remote_host
: The remote server's address.
The ExecStart
command uses the -N
option to tell SSH that no commands will be executed, and the -L
option to set up local port forwarding. The Restart=always
directive ensures that the service restarts if it fails, and RestartSec=5s
sets a 5-second delay before restarting. Note that you might encounter issues with systemd if you use the -f
option.
Reload Systemd and Restart the Service
After updating the service file, reload systemd
and restart the SSH tunnel service:
sudo systemctl daemon-reload
sudo systemctl restart sshtunnel
Enable the Service at Boot
sudo systemctl enable sshtunnel
Verify the Tunnel
sudo systemctl status sshtunnel
Conclusion
By using systemd
, you can create a persistent SSH tunnel that automatically reconnects if the connection is lost. This approach ensures a reliable and secure connection to your remote services without manual intervention. The steps outlined above provide a robust solution for maintaining SSH tunnels, leveraging the powerful features of systemd
.