Connect to MySql database using SSH tunneling on a remote host with a specific mysql host

I use Jsch to connect to a remote mysql database, where the ssh host does not match the mysql host, as shown in the upper half in the figure below: enter image description here

Below is the code that I use to connect SSH:

private static void connectSSH() throws SQLException { try { java.util.Properties config = new java.util.Properties(); JSch jsch = new JSch(); jsch.setLogger(new MyLogger()); session = jsch.getSession(sshUser, sshHost, 22); jsch.addIdentity(SshKeyFilepath, sshPassword); config.put("StrictHostKeyChecking", "no"); config.put("ConnectionAttempts", "3"); session.setConfig(config); session.connect(); System.out.println("SSH Connected"); Class.forName(driverName).newInstance(); int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort); System.out.println("localhost:" + assinged_port + " -> " + sshHost + ":" + remotePort); System.out.println("Port Forwarded"); } catch (Exception e) { e.printStackTrace(); } } 

and ultimately connect to the database using the following code:

  Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:" + localPort, dbUser, dbPassword); 

I can successfully make an SSH connection, but execution is suspended when the line below:

 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:" + localPort, dbUser, dbPassword); 

I double-checked my SSH and database credentials by connecting to the command line. I can connect to the database using

 mysql -h host1 -u "myusername" -p"mypasswordhere" 

I suppose the problem may be due to the fact that on the remote host, the mysql host is not localhost, but host1 , which I do not know where to specify in jdbc url.

+5
source share
2 answers

Well, this was the wrong port forwarding method, which was the main cause of the problem:

instead:

 int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort); 

he should have been

 int assinged_port = session.setPortForwardingL(localPort, localSSHUrl, remotePort); 

Now the connection is working fine.

+2
source

I know this is old, but localSSHUrl is really the host that you would use when you logged in to SSH.

In short, this is usually "localhost" when you try to connect to databases as a local user.

 int assigned_port = session.setPortForwardingL(localPort, "localhost", remotePort); 

Many examples use remote_host to connect to both SSH and the database through port forwarding, but if you only have local access to the database, it will not be able to connect.

0
source

Source: https://habr.com/ru/post/1240431/


All Articles