Autossh is a utility that allows you to automatically restart SSH tunnels if they are disconnected or interrupted. This can be particularly useful if you need to maintain a persistent connection to a remote server over an SSH tunnel. In this article, we will explain how to install and use Autossh on Linux.
Step 1: Install Autossh
Autossh is available in most Linux distributions’ package repositories. To install it, open a terminal and run the following command:
sudo apt-get install autossh
If you are using a different package manager, you can search for and install the “autossh” package using the appropriate command.
Step 2: Set up an SSH tunnel
Before we can use Autossh, we need to set up an SSH tunnel that it can manage. In this example, we will create a tunnel that forwards local port 8080 to port 80 on a remote server.
To create the tunnel, run the following command in a terminal:
ssh -L 8080:localhost:80 remote-user@remote-server
This command will establish an SSH connection to the remote server and create a tunnel that forwards traffic from port 8080 on your local machine to port 80 on the remote server.
Once the SSH tunnel is established, you can test it by opening a web browser and navigating to http://localhost:8080. If everything is set up correctly, you should see the default web page for the remote server.
Step 3: Use Autossh to manage the SSH tunnel
Now that we have an SSH tunnel set up and working, we can use Autossh to automatically restart the tunnel if it is disconnected or interrupted.
To use Autossh, we need to modify the SSH command used to create the tunnel. Here’s an example:
autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N -f -L 8080:localhost:80 remote-user@remote-server
This command is similar to the SSH command we used to create the tunnel earlier, but it includes some additional options that tell Autossh to manage the tunnel.
- The
-M 0
option tells Autossh to use a built-in monitoring port to detect if the SSH tunnel has disconnected. - The
-o "ServerAliveInterval 30"
and-o "ServerAliveCountMax 3"
options tell Autossh to send keepalive packets every 30 seconds, and to attempt to reconnect if three consecutive keepalive packets fail. - The
-N -f
options tell SSH to create the tunnel in the background without executing any remote commands.
Step 4: Test Autossh
To test Autossh, disconnect your internet connection or manually stop the SSH tunnel by pressing `CTRL + C`. Autossh should detect that the tunnel has been disconnected and automatically restart it.
You can verify that the tunnel has been restarted by navigating to http://localhost:8080 in your web browser.
Conclusion
In this article, we have explained how to install and use Autossh on Linux. Autossh can be a valuable tool for maintaining persistent SSH connections over unstable or unreliable network connections. By using Autossh, you can ensure that your SSH tunnels remain operational even if the connection is interrupted.