Two servers: remote1 and remote2. Remote1 is behind a firewall.
Situation 1: Port Forwarding
You want to be able to access remote2’s port 2222 as though it was on port 1111 of remote1. That is, telnetting to remote1:1111 will transparently connect you to remote2:2222. On remote1, type:
remote1:~$ ssh -L 1111:remote1:2222 user@remote2
Use this when you want to access services running on a remote server as though it was on the local network, such as accessing your iTunes share remotely.
Situation 2: Reverse Port Forwarding
You want to be able to access remote1’s port 2222 as though it was on port 1111 of remote2. That is, you want to be able to connect to the server that is behind the firewall, using the other server as a proxy of sorts, punching through the firewall. On remote1, type:
remote1:~$ ssh -R 1111:remote1:2222 user@remote2
Use this when you want to be able to remotely access a server that’s behind a firewall.
To ensure that its connection is restarted if it dies unexpectedly, you can type:
while true ; do ssh -R 8022:localhost:22 suso@my.home.ip.address; \
sleep 60 ; done
If you’re running this on a Mac, you’ll want to play around with the launch daemon, launchd and its magical XML files. I recommend just using Lingon instead.
Source
Many thanks to Suso’s SSH on Linux Tutorial. It goes over some other useful stuff, too.
Aidan Findlater Impersonal linux, mac os x, port forwarding, ssh