2016-01-12 91 views
5

我使用的是Jsch连接到远程mysql数据库,其中ssh主机与mysql主机不一样上半部分如下图: enter image description here用特定的mysql主机在远程主机上通过SSH隧道连接到MySql数据库

下面是我使用了SSH连接的代码:

private static void connectSSH() throws SQLException { 
    try { 
     java.util.Properties config = new java.util.Properties(); 
     JSch jsch = new JSch(); 
     jsch.setLogger(new MyLogger()); 
     session = jsch.getSession(sshUser, sshHost, 22); 
     jsch.addIdentity(SshKeyFilepath, sshPassword); 
     config.put("StrictHostKeyChecking", "no"); 
     config.put("ConnectionAttempts", "3"); 
     session.setConfig(config); 
     session.connect(); 

     System.out.println("SSH Connected"); 

     Class.forName(driverName).newInstance(); 

     int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort); 

     System.out.println("localhost:" + assinged_port + " -> " + sshHost + ":" + remotePort); 
     System.out.println("Port Forwarded"); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

,并最终使用下面的代码连接到数据库:

Class.forName("com.mysql.jdbc.Driver"); 
     Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:" + localPort, dbUser, dbPassword); 

我能够做成功的SSH连接,但执行是越来越挂了的时候,在下面的一行:

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:" + localPort, dbUser, dbPassword); 

我有双重通过连接在命令行检查了我的SSH和数据库的凭据,我能够连接到使用

mysql -h host1 -u "myusername" -p"mypasswordhere" 

我想这个问题可能是由于数据库的远程主机上的MySQL主机不是本地主机,但主机1我不知道在jdbc url中指定的位置。

+0

你是否在你的本地和远程机器上“挂起”netstat?可能是防火墙/路由问题 – Jan

+0

做了我的“本地”,而挂起它说“ESTABLISHED”连接使用我的本地端口forwaded到远程机器 – Anirudh

+1

所以隧道似乎没问题。你有你的隧道主机的netstat? – Jan

回答

2

那么它是端口转发的错误的方式,这是问题的根源:

代替:

int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort); 

它应该是

int assinged_port = session.setPortForwardingL(localPort, localSSHUrl, remotePort); 

连接运行正常现在。

+0

我有类似的问题。你能发布整个代码片段吗? – Cafebabe

+0

嗨Anirudh。我也面临同样的问题。你能告诉我什么是localSSHUrl吗? – Vinay

相关问题