April 18, 2012

Access Your MySQL Server Remotely Over SSH

Access Your MySQL Server Remotely Over SSH

So you’ve got MySQL on your web server, but it’s only opened to local ports by default for security reasons. If you want to access your database from a client tool like the MySQL Query Browser, normally you’d have to open up access from your local IP address… but that’s not nearly as secure.

So instead, we’ll just use port-forwarding through an SSH tunnel, so your MySQL client thinks it’s connecting to your localhost machine, but it’s really connecting to the other server through the tunnel.

You will need the following software:

Putty:
You can download putty from the url: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html

Run the downloaded putty.exe file. You will get a window like this and enter the Hostname or IP Address.

For eg:
Hostname or IP Address: 10.5.7.51

Now click open

You will get a session and for saving that session right click on windows and take Change Settings as shown below:

Below Saved Sessions enter any name for eg: mysql-ssh and click on save.

Now again take putty and click on whichever connection name you wish to use for the secure tunnel.

Click "Load"
Go to Connection > SSH > Tunnels

Enter MySQL connection information

The "Source port" is the local port your MySQL Administrator will connect to instead of the remote (server) port it normally would. This can be any port and we can use .
The "Desitination" is the address and port of your actual MySQL Server. But since your SSH connection will be considered "local" to your MySQL Server, you should use either "127.0.0.1" or "localhost" depending on what works best. Then specify your mysql port so that Destination will be as follows:

127.0.0.1:3306

Make sure the information in "Source port" and "Destination" are correct, that the "Local" radio button is selected and click "Add".

You should now see the new tunnel information displayed as shown.

Go back to the main Putty screen and save the connection.

Now you can open ssh session by entering the user name and password.

Once you’ve got the ssh tunnel going, you can open up any mysql client and enter in the details for your remote server.

Since your connection will now be through the secure tunnel created by Putty, your "Server Host" will now be local so use "127.0.0.1".

The "Port" should be set to the same port you set for Source port earlier.

Once the connection settings are correct, click "OK" and you should then be able to succesfully connect to your MySQL server except now, through a secure tunnel!