Thursday, December 13, 2007

MySQL ssh tunnel

1.
On your home machine:
ssh -L 3307:domain.name.of.mysqlserver:3306 username@domain.name.of.gatewayserver

Ex:
$ ssh -L 3307:dbserver:3306 ananth@xxx.xxxxxxx.xxx

This will open a tunnel, listening on localhost:3307 and forwarding everything to mysqlserver:3306, and doing it all via the ssh service on the gateway machine.

2.
Now, on your local machine, execute a mysql connection like so:
mysql -u username -p -h 127.0.0.1 -P 3307 databasename

Ex:
C:\Program Files\MySQL\MySQL Server 5.0\bin>mysql -u USERNAME -pPASSWORD -h 127.0.0.1 -P 3307 DATABASENAME

In other words, mysql thinks it's connecting to localhost, but on a different port. In fact, the connection is being made securely to the remote mysql server, via the gateway machine and the local "mouth" of the ssh tunnel on your own machine.

3.
When you're finished with your mysql session, log out of the session on the gateway machine. That will properly close the tunnel.

No comments: