Ubuntu: How to Setup a SSH Tunnel via a Terminal CodeUnit 26 OCT 2012

SSH tunnels are useful beasts in that they allow you to communicate with machines and ports on a private network which are not directly accessible to the external world, by building a bridge between your local machine and a machine in the walled off network to which you happen to have SSH access to.

The diagram below shows you an example whereby to gain access to a Oracle server on Port 1521, you would first SSH into a linux box on the inside network and then create a SSH tunnel which would transport traffic between your machine and the Oracle server.

Another example could be if you have MySQL installed on your server but have cut off external access to the database server, leaving only SSH open. In this case, you would connect into the box via SSH and create a tunnel to the MySQL database server on localhost port 3306.

To create a SSH tunnel is fairly simple and can be created with this command:

ssh -f remote-server.net -p 22 -l myusername -L 3307:localhost:3306 -N

The line above first connects to remote-server.net via SSH on port 22 using the user name ‘myusername’, and then sets up a SSH tunnel connecting port 3307 on your local PC (i.e. and hooking it up to port 3306 on the remote-server.net box itself. Of course you could have created a connection to any other box that remote-server.net has direct access to.

You should be prompted for a password when running this command. Note that the -f switch means that this process will be started in the background and the trailing -N instructs OpenSSH not to execute the command on the remote server.


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.