Ok - so I have been working on this for some time (sometimes not working on it), and I am ALMOST there but not yet. I am trying to tunnel into a mysql db and was able to successfully connect ssh using Jsch. But when I try to connect to the database, it gives me an "Access denied for user 'usernamne'@'localhost' (using password: YES)
Here is the following code: (of course I masked out sensitive info)
public void connect(){
String user = "user";
String password = "password";
String host = "host.com";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = null;
Properties info = new Properties();
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
jsch.addIdentity("/Users/user/.ssh/id_rsa", password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
if(session.isConnected()){
session.disconnect();
}
session.connect();
conn = DriverManager.getConnection("jdbc:mysql://localhost:4417/dbname","dbuser", "dbpassword");
System.out.print("Connection successful!" + "\n\n");
System.out.print("Connection:" + conn + "\n\n");
Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT * FROM TABLENAME limit 1");
System.out.print(resultSet);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (JSchException j){
j.printStackTrace();
}
}
I've read other posts on here but I have not found the exact solution to my problem. I am able to ssh in correct. And what's even more interesting is that if I do the same exact procedure command_line, it works fine. So I don't know why it wouldn't work here.
Try this. it might help you . Already tested in my setup. Enjoy. :)
create db user in remote mysql db.
CREATE USER 'myuser'@'clientip' IDENTIFIED BY 'pass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'pass';
grant ALL ON mydb.* to 'myuser'@'clientip';
grant ALL ON mydb.* to 'myuser'@'%';
FLUSH PRIVILEGES;
Code for ssh tunneling.