Able to establish SSH tunnel connection using Jsch. Trying to do a simply query on the MySQL database and an error is returned stating that there was a "communications link failure".
The code is below and I have tried changing a few things to troubleshoot. I am able to connect to the server if I establish an external SSH tunnel through Putty first and change the ip address to the actual address instead of the local host.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class DB_Connection {
static int assigned_port;
public static void main(String[] args) throws Exception {
//DB Credentials
String rhost = "das.ssh.wpengine.net";
String strUser = "das";
String strPwd = "longpassword";
String strSerName = "wp_das";
//Connect Session
Session ses = connectSession(rhost);
//Connect Database
try(
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wp_das", "das", "LongPassword");){
System.out.println ("Database connection established");
} catch(SQLException e) {
System.out.println(e.getMessage());
//Execute query
//Disconnect Database
// con.close();
//Disconnect Session
// ses.disconnect();
}
}
public static Connection getConnection(String strUser, String strPwd, String strSerName) throws Exception {
// load driver class
String strurl = "jdbc:mysql://127.0.0.1:3306/wp_das";
Connection con = DriverManager.getConnection(strurl, strUser, strPwd);
return con;
}
public static void executeQuery(Connection con) throws SQLException{
String strQry = "SELECT * FROM wp_das.comments";
PreparedStatement pst = con.prepareStatement(strQry);
ResultSet rs = pst.executeQuery();
// String strOutput = qry.getXMLString();
// System.out.println(strOutput);
}
public static Session connectSession(String rhost) {
Session session = null;
String user = "das";
String host = "das.ssh.wpengine.net";
int port = 22;
String privateKey = "c://users//ed25519eclipse";
try{
JSch jsch=new JSch();
jsch.addIdentity(privateKey); //public key authentication
session=jsch.getSession(user, host, port); //start new session
int lport = 3306;
int rport = 3306;
session.setConfig("StrictHostKeyChecking", "no"); //bypass prompt
System.out.println("Establishing Connection");
session.connect(); //opens new session
System.out.println("Port Connected");
assigned_port = session.setPortForwardingL(lport, rhost, rport);
System.out.println("Port Forwarded");
} catch (Exception e) {
System.err.print(e);
}
return session;
}
}
The output in the console is below: Establishing Connection Port Connected Port Forwarded Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.