SSH Through a Router Without Port Forwarding
If you want to establish an SSH connection to your “linux server” from the outside without configuring port forwarding on your router, you can use SSH remote port forwarding. This technique allows you to connect to an external server (let’s call it “my_other_server”) and have it forward traffic back to your “linux server.” Here’s how you can do it:
-
SSH from linux_server to my_other_server:
Open a terminal on your “linux server” and use the following command to initiate an SSH connection to “my_other_server,” specifying remote port forwarding:
1
[user@linux_server]$ ssh -R 8022:localhost:22 my_other_server.com
Explanation: This command connects to “my_other_server” and opens port 8022 on that server, which will forward traffic back to your “linux_server” on port 22.
-
SSH from my_other_server back to linux_server:
Now that you have established the remote port forwarding, you can SSH from “my_other_server” to your “linux_server” through the established tunnel. On “my_other_server,” open a terminal and use the following command:
1
[user@my_other_server]$ ssh -p 8022 localhost
Explanation: This command connects to “my_other_server” itself but uses port 8022, which is being forwarded to your “linux_server.” As a result, your SSH traffic is tunneled back to your “linux_server.”
-
Handling Connection Stability:
If you encounter problems with the initial tunnel dropping out, you can take several measures:
-
Keepalive Settings: Adjust the SSH keepalive settings to ensure the connection stays alive. You can add the following options to your SSH command on “my_other_server”:
1
[user@my_other_server]$ ssh -o ServerAliveInterval=60 -p 8022 localhost
This setting sends a keepalive packet every 60 seconds to maintain the connection.
-
Use
autossh
:autossh
is a tool that helps maintain SSH tunnels. It automatically restarts SSH sessions and keeps tunnels alive even if they disconnect. You can install it and use it in place of regular SSH like this:1
[user@my_other_server]$ autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -p 8022 localhost
This command uses
autossh
with specified options to ensure a stable SSH tunnel.
-
By following these steps and considering connection stability measures, you can SSH to your “linux server” through a router without the need for port forwarding on the router itself.