Connect to remote database through SSH

 

In this example, we will create a Java program to connect to a remote database server through an SSH tunnel.

We consider that we have a MySQL database instance running on a remote server : sec.keylesson.com. In fact, we can’t access the instance from outside the server, in this case we need to create an SSH tunnel to the database instance.

To connect to the remote server, we will use the JSch which is a Java implementation of SSH2. We need then to include the jsch-0.1.53.jar to our project to use the Jcrat utilities.

In the Java program below, we will do the following steps :

  • Open an SSH connection to the remote server.
  • Doing a local port forwarding to make SSH create a tunnel that opens up a new port (3306) on the remote server, and connects it to the local port (3307) on our machine.
  • Connect to the database from the local machine (localhost) on port 3307.

 

1. Connect using username and password

 

2. Connect using ssh file and passphrase

Replace the following code :

with the code below :