【发布时间】:2016-08-27 16:17:22
【问题描述】:
所以我正在创建一个到我的远程 MySQL 服务器的 SSH 连接。我可以通过 shell 执行 ssh -v user@host,所以我知道我的主机 ip、用户名和密码是正确的。
这是我用来执行此操作的代码:
int lport=5656;
String rhost="host";
String host="host";
int rport=3306;
String user="root";
String password="pass";
String dbuserName = "root";
String dbpassword = "pass";
String url = "jdbc:mysql://localhost:"+lport+"/lg4";
String driverName="com.mysql.cj.jdbc.Driver";
Connection conn = null;
Session session= null;
try{
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName(driverName).newInstance();
conn = DriverManager.getConnection (url, dbuserName, dbpassword);
System.out.println ("Database connection established");
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null && !conn.isClosed()){
System.out.println("Closing Database Connection");
conn.close();
}
if(session !=null && session.isConnected()){
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
}
控制台播放:
“端口转发”来自 System.out.println(“端口转发”);
所以我知道它确实进行了端口转发,问题出在这一行:
conn = DriverManager.getConnection (url, dbuserName, dbpassword);
错误是:
CommunicationsException:通信链路故障
所以我开始尝试寻找解决这个问题的方法,我发现了一系列可能的解决方案和问题:
- JDBC URL 中的 IP 地址或主机名错误。
- 本地 DNS 服务器无法识别 JDBC URL 中的主机名。
- JDBC URL 中的端口号缺失或错误。
- 数据库服务器已关闭。
- 数据库服务器不接受 TCP/IP 连接。
- 数据库服务器已用完连接。
- Java 和 DB 之间的某些东西阻塞了连接,例如防火墙或代理。
好的,我开始一一讨论,缩小问题范围:
- 我知道我的 IP 是正确的,因为我能够通过 shell 访问它并且它会进行端口转发。
- 一模一样
- 我添加了我转发到本地主机的端口,所以我怀疑这是问题所在。
- 服务器没有关闭,我什至重新启动以确保一切正常。
- 我配置了 MySQL,注释 #bin-address,我无法注释 skip-networking,因为 bin-address 现在是默认值。
- 这是怎么发生的?我不知道这个。
- 我的防火墙已关闭。
我做错了什么?
【问题讨论】:
标签: java mysql sockets jdbc ssh