Reputation: 2326
I am using Jsch to connect to the remote mysql database where the ssh host is not the same as the mysql host as shown by the Upper half of the picture below:
Below is the code I am using for SSH Connection:
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 eventually connecting to the database using the code below:
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:" + localPort, dbUser, dbPassword);
I am able to do an SSH connection successfully but the execution is getting hung up when at the line below:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:" + localPort, dbUser, dbPassword);
I have double checked my SSH and database credentials by connecting on commandline I am able to connect to the database using
mysql -h host1 -u "myusername" -p"mypasswordhere"
I suppose the problem might be due to the fact that on remote host the mysql host is not localhost but host1 which I don't know where to specify in the jdbc url.
Upvotes: 7
Views: 6526
Reputation: 41
I know this is old, but the localSSHUrl is really the host that you would use when you are logged in to SSH.
In short, this is usually “localhost” when you are trying to connect to databases as a local user.
int assigned_port = session.setPortForwardingL(localPort, “localhost”, remotePort);
Many examples use remote_host to connect both to the SSH and to the database via port forwarding, but if you only have local access to the database, it will fail to connect.
Upvotes: 4
Reputation: 2326
Well it was wrong way of port forwarding that was the root cause of the problem:
instead of:
int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
it should have been
int assinged_port = session.setPortForwardingL(localPort, localSSHUrl, remotePort);
The connection runs fine now.
Upvotes: 2