How to create a persistent ssh tunnel using autossh

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:

For example, to create a tunnel that forwards local port 8080 to remote host example.com on port 80, the command would be:

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.

Then use the following command to create a persistent tunnel:

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:

This command creates a persistent tunnel that forwards local port 8080 to remote host example.com on port 80

Rate this post

Leave a Reply