How to build a reverse ssh mysql tunnel

Suppose you need to connect to a mysql database on a server (the "DB" server) to which you have been firewalled out of. Not a problem if you can connect to a server (the "TUNNEL" server) that has been let through the firewall. No problem at all. It's a little bit of a problem. But you're stalwart.

Here's what you do:

  1. ssh into the DB server:
  2. use the screen utility to allow you to detach your terminal, and still keep the tunnel open:
  3. Open the tunnel to the TUNNEL server. Let's say you want to connect to the db server on port 3306. Pick an arbitrary port for your TUNNEL server (3316, for instance):
    ssh -R 3316:localhost:3306
  4. You are now on the TUNNEL server. You want to keep the connection open, at that point, and can do a cheesy keepalive:
    while true ; do echo keepalive ; sleep 60 ; done
  5. Now detach by pressing ctrl-A, then d. This returns you to the DB server but the tunnel to the TUNNEL server remains open.

That's it! Your reverse tunnel is open. If you want to connect to the DB server directly from the TUNNEL server, then your command is:
mysql -h -u USERNAME -p -P 3316

If you are on another server, you will have to tunnel into the TUNNEL server first:

ssh -L 3308:

After that, you can connect with the command:

mysql -h -u USERNAME -p -P 3308

No comments:

Post a Comment