In my work, I used SSH a lot for remote access, including Amazon cloud server. It works with the following simple command,
For example, the remote machine has an IP of 22.214.171.124, and the user name is test, then we simply enter the following command,
This requires the remote side to have a public IP address. If we want to ssh to a computer which sits behind firewall and NAT, then the computer won’t be visible to us and SSH won’t work.
That’s where the reverse SSH comes into play.
Reverse SSH doesn’t require the destination to have a public IP address, instead the public IP address could be with the source side, or a middle machine between source and destination. We’ll cover both cases below.
(Throughout this tutorial, we’ll use 126.96.36.199 as public IP for our machine, no matter it’s at the source side or dest side, and “test” as the username for the machine with public IP.)
1. Access Remote Side from Source with Public IP
First, consider the case we have a public IP address at source, and we want to access a destination computer in a private network.
At the destination, type the command below,
ssh –R 12345:localhost:22 firstname.lastname@example.org
This command will create a tunnel between the source addr (188.8.131.52:12345) and the destination address (localhost[with private ip]:22).
Then at the source side, we ssh to local port 12345 by,
ssh dest_user_name@localhost –p 12345
This command will ssh to source port 12345, which has been connected with the remote side in previous step.
Therefore, the SSH tunnel is established as below,
dest addr (private_ip:22) <= source addr 1 (184.108.40.206:12345) <= source addr 2(220.127.116.11 : port_used_by_source_ssh_client)
Note that you’ll need both connections active to access the destination. In order to keep it alive, you can run command like “top” and “watch” to ensure there’s some data transmission.
Or you can add the following line to the /etc/ssh/ssh_config file:
The client will send keep alive message every 60 seconds in this case.
2. Connect Remote Side using Private IP, with Public IP as Middle Man
Now consider a situation where both source and dest have private IP addresses, then the public IP machine can serve as middle man.
We simply SSH to middle man first, then the reset is the same as previous case.
So first at source computer,
After ssh to middle computer, at the middle computer,
ssh –R 12345:localhost:22 email@example.com
Finally, at source computer (probably you’ll need to open another console window),
ssh localhost –p 12345