Command Line SSH Tunnel Port Forwarding

Tutorial on command line SSH tunneling, port forwarding. How to setup an SSH tunnel using bash scripting.

SSH port forwarding (aka tunneling) is useful for getting into remote systems securely. If you need to access a database server, source repository, or other service that is blocked off by a firewall (except for ssh), a tunnel will let you access as them if you are on the local network.  The traffic between your machine and the server runs over the encrypted SSH connection.

SSH GUI based clients have control panels that allow you to setup tunnels. Sometimes, it is necessary to automate such a task on the shell level.

#using the command line only, open ssh tunnel to mysql database
$ ssh -l youruser yourhost.com -p 22 -N -f -C -L 3306:yourdbserver.com:3306

Now when you connect to localhost:3306 for MySQL, you are actually connecting to the remote database server. If you are running MySQL on your local machine as well, then select another open local port (eg, 3307:yourdbserver.com:3306), then connect to localhost:3307 to use the tunnel.

Argument summary:

  • -l login name
  • -p remote host port (It is best to connect to ssh on something other than the default port to shake off automated attacks. Change sshd.conf and/or the port mapping on your firewall. For example :2210 external maps to :22 internal for your ssh boxes that are allowed to accept outside connections.)
  • -N do not execute a remote command
  • -f requests SSH to go to background
  • -L port:host:hostport (port = local port, host and hostport are where you want the tunnel to point to. This does not have to be the box you are ssh-ing to!)
  • -C compression – optional

The command will ask for a password after it is executed. Then it will go into the background, running as a system process. To make this run unattended, such as in a nightly cron script, use ssh-keygen to setup trusted authentication between the local and remote host.

How to tell if the tunnel is working:

#check for ssh process with the parameters specified above
$ ps aux | grep ssh
#or, try to talk to it
$ telnet localhost 3306

When you are done with the tunnel and want to shut if off:

#find the tunnel that was setup on port 3306 and shut it down
#alter "3306:" to match the local port tunnel to shut off
ps -fU root -C ssh | grep "ssh -l" | grep "3306:" | awk '{print $2}' | xargs kill
This entry was posted in Sys Admin and tagged , , . Bookmark the permalink.

Comments are closed.