Finally, I got it, you want to connect mysql database service using SSH tunnel only, you don't want to open the firewall and want to access database via JumpBox only.
I have used JSch liberary to do SSH tunning.
Here goes your code.
import java.sql.DriverManager;
import java.sql.SQLException;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.sql.Connection;
public class MySqlConnOverSSH {
public static void main(String[] args) throws SQLException {
int local_proxy_port=4567;
String database_host="rdbms.strato.de";
String ssh_host="ssh.strato.de";
int database_port=3306;
String user="ssh_username";
String privateKey = "In case you want to use private key to do SSH";
String password="sshpassword";
String dbuserName = "yourDBName";
String dbpassword = "YourDBPass";
String url = "jdbc:mysql://localhost:"+local_proxy_port+"/your-database-name";
String driverName="com.mysql.jdbc.Driver";
Connection conn = null;
Session session= null;
try{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
//Only in case you need to access SSH using key.
//jsch.addIdentity(privateKey);
session=jsch.getSession(user, ssh_host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
int assinged_port=session.setPortForwardingL(local_proxy_port, database_host, database_port);
System.out.println("localhost:"+assinged_port+" -> "+database_host+":"+database_port);
System.out.println("Port Forwarded");
Class.forName(driverName).newInstance();
conn = DriverManager.getConnection (url, dbuserName, dbpassword);
System.out.println ("Connected!!!");
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null && !conn.isClosed()){
System.out.println("Hurry Done!!");
conn.close();
}
if(session !=null && session.isConnected()){
System.out.println("Hurry Done!! Closing SSH");
session.disconnect();
}
}
}
}
Make sure to include to include mysql-connector-java-xxx-bin.jar;
to your classpath
. Where xxx is version of mysql jdbc jar
e.g. 5.0.8
Post further error you see after running this code if it doesn't work. I could reattempt to answer.
2013 - Lost connection to MySQL at 'reading intial communication packet', system error: 0
Screenshot of the info I got from PuTTy: puu.sh/zkJ5J/2b8f844115.png And two screenshots from my NaviCat config: puu.sh/zkJc6/c848d3ebd2.png and puu.sh/zkJdv/6feb584e3a.png – Brightworkrdbms
pointing to?nslookup rdbms
. Then using whatever that as host? – Abott