This article will cover how to use the port-forwarding feature in SSH to accomplish tunneling from one machine to another.
SSH, or Secure Shell, has the ability to proxy connections both forward and backwards, by opening a port on either the local machine running the SSH client, or the remote SSH server (if you have privileges to do so).
For example, if you want to connect to remote host on port 80, but you don’t have direct access to reach that machine because of firewall or network restrictions, the SSH client can listen on a local port and pretend that it is the remote machine. All connections to that port will be sent through the SSH server to the remote host.
Localhost:80 --> SSH SERVER --> REMOTE HOST:80
Todo: Insert better illustration here.
You can also tunnel requests the opposite direction, by opening a port on the remote server and tunneling all connections backwards up through the SSH client to your local machine. This is often used to open a remote X session on a client machine, or to allow reverse tunneling into a machine behind an extremely restrictive firewall that doesn’t allow incoming connections.
To forward from one machine to another, you need to use the -L switch when creating an ssh connection.
ssh -L <localport>hostname<remoteport> <username>@<servername>.
ssh -L 3306:localhost:3306 email@example.com
Tunnel All Connections Using SOCKS Proxy
Tunnel to a MySQL Server on the SSH Server
Use this syntax, you can simply use the -L option with localhost as the server to be forwarded to. In this case, localhost is actually the ssh server, because this option is referenced from the point of view of the server you are connecting to (in this case sshserver).
ssh -L 3306:localhost:3306 geek@sshserver
Note that if you are running a local mysql server, you’ll have to change the first parameter to another port, for instance 13306:localhost:3306. Then you’ll have to specify the option in the mysql client to use another port when connecting.
Tunnel to a MySQL Server on Another Server
Use this syntax, replacing mysqlserverIP with the actual IP of the MySQL server.
ssh -L 3306:mysqlserverIP:3306 geek@sshserver
Note that if you are running a local mysql server, you’ll have to change the first parameter to another port, for instance 13306:mysqlserverIP:3306. Then you’ll have to specify the option in the mysql client to use another port when connecting.
Tunnel to another SSH Server
Programmer by day, geek by night, The Geek, also known as Lowell Heddings, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on Google+ if you'd like.
- Published 07/16/10