Table of Contents
Creating a persistent SSH tunnel involves two steps: first, creating the tunnel itself, and second, ensuring that the tunnel is automatically re-established if the connection is lost.
Creating the SSH Tunnel
The basic command for creating an SSH tunnel is:
1 |
ssh -L [local port]:[destination host]:[destination port] [username]@[remote host] |
For example, to create a tunnel that forwards local port 8080 to remote host example.com on port 80, the command would be:
1 |
ssh -L 8080:example.com:80 user@remotehost |
Making the Tunnel Persistent
One way to ensure that the tunnel is re-established if the connection is lost is to use a tool like autossh.
First, install autossh on your local machine if it’s not installed.
1 |
sudo apt-get install autossh |
Then use the following command to create a persistent tunnel:
1 |
autossh -f -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -L [local port]:[destination host]:[destination port] [username]@[remote host] |
The options used in this command are: -f: run in the background -M 0: disable monitoring of the connection -o “ServerAliveInterval 30”: send a keepalive packet every 30 seconds -o “ServerAliveCountMax 3”: if no response is received after 3 keepalive packets, assume the connection is down
You can also add this command to your startup script so that the tunnel is automatically established when your machine is rebooted.
Example:
1 |
autossh -f -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -L 8080:example.com:80 user@remotehost |
This command creates a persistent tunnel that forwards local port 8080 to remote host example.com on port 80