2016-01-12 90 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

相關問題