I have two servers (Both running CentOS 5.5 64-Bit)

One server is connected to a public network and has a public IP address which I can use to SSH into it remotely. The other server is connected to Server 1 through a private network.

I would like to know how I can forward a port (say 20222) on server 1 to port 22 on server 2 so that I can connect to server 2 using any SSH client by using the public IP of server 1 and port 20222.

The public network of server 1 is connected through interface eth0 and private network is connected through eth1

Thanks a lot.

Regards, Kalpesh


You can easily do this creating a ssh tunnel :

ssh -L 20222:server_2_private_IP_address:22 server_1_public_IP_address

You could also add this to your ~/.ssh/config if you have one as:

Host foo
  Hostname server_1_public_IP_address
  User ...
  LocalForward 20222 server_2_private_IP_address:22

After starting a ssh to server_1_public_IP_address, you should be able to start a new ssh session to server_2 using

ssh -p 20222 localhost

Never tried it, but should work with any ssh client, point it to localhost and por 20222.

And read

man ssh

All this is explained in there.


Assuming server 1 has external address and internal address, and server 2 has internal address and no existing default route:

on server 1:

iptables -t nat -A PREROUTING -p tcp --dport 20222 -i eth0 -j DNAT --to-destination
echo 1 > /proc/sys/net/ipv4/ip_forward

on server 2:

route add default gw

None of these settings is persistent, that is, they won't survive a reboot. If they work, we can discuss how to make them permanent.


You can also install stone (tcp/udp open source tunneling software) by running and then run the following command as root

wget http://www.gcd.org/sengoku/stone/stone-2.3e.tar.gz
tar xzf ./stone-2.3e.tar.gz
cd ./stone-2.3d-
make linux
cp ./stone /usr/bin/
cd ../
rm -Rf ./stone-2.3d-

then as user run the following command

stone -D server1:20222/tcp server2:22/tcp

MadHatter has the iptables answer for you if you want to go that route.

For quick and dirty redirects during migrations and stuff, I have used redir

Something like this on Server 1:

  redir --lport=20222 --caddr=$IP_OF_SERVER_2 --cport=22

Again, that just runs in the foreground and won't survive a reboot, but it's such a handy command that I thought it belonged in this discussion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.