我需要通过ssh连接连接到Mysql RDS DB,我尝试的是打开ssh隧道,然后连接到该DB,但是它没有工作。
下面是我的代码:
int lport = 3306;
String host = "10.254.64.135";
String rhost = "localhost";
int rport = 8000;
String user = "ubuntu";
String dbuserName = "someusername";
String dbpassword = "somepassword";
String dburl = "jdbc:mysql://somedbhost.us-east-1.rds.amazonaws.com:3306";
String driverName = "com.mysql.jdbc.Driver";
String driverName2 = "org.gjt.mm.mysql.Driver";
Session session = null;
try {
final java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
final JSch jsch = new JSch();
session = jsch.getSession(user, host, 22);
jsch.addIdentity("C:\\Users\\rop\\workspace\\awskey.pem");
session.setConfig(config);
session.connect();
System.out.println("Connected through SSH");
final int assinged_port = session.setPortForwardingL(rport, host,lport );
System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName("com.mysql.jdbc.Driver").newInstance();
//String url = "jdbc:mysql://localhost:" + rport + "/" + db;
con = DriverManager.getConnection(dburl, dbuserName, dbpassword);
System.out.println("Mysql Database connection established");
System.out.println("DONE");上面的代码崩溃,下面是异常,这一行中的崩溃是"con = DriverManager.getConnection(dburl,dbuserName,dbpassword)“:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败最后一次成功发送到服务器的数据包是0毫秒前。驱动程序没有从服务器接收任何数据包。
也就是说,当我们从mysql工作台连接时,它确实正常地连接,在快照下面:

请注意,ssh主机ip与db主机ip不同。
谢谢。
发布于 2016-04-20 14:19:00
您需要将JDBC url中的主机名和端口替换为localhost和您正在转发的本地端口(您称之为rport )。
dburl = "jdbc:mysql://localhost:" + rport;
此外,我不确定MySQL JDBC驱动程序是否支持连接到数据库服务器,而不指定数据库名称:
dburl = "jdbc:mysql://localhost:" + rport + "/yourdatabasename";
此外,如果MySQL服务器与SSH服务器不在同一台计算机上运行,请确保可以从SSH服务器连接到数据库服务器。默认情况下,MySQL不允许远程连接。
https://stackoverflow.com/questions/36745762
复制相似问题