2015-10-05 48 views
0

我尝试通过ssh隧道创建到远程服务器的连接。在我的尝试中,我使用了jsch和putty。DataSource的getConnection()忽略端口

int sshPort = 22; 

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("sshUser", "sshHost", sshPort); 
    session.setPassword(sshPassword); 
    session.setConfig(config); 
    session.connect(); 

    session.setPortForwardingL(8806, "127.0.0.1", 3306); 

    BasicDataSource basicDataSource = new BasicDataSource(); 
    basicDataSource.setDriverClassName("com.mysql.jdbc.Driver"); 
    //I can type here any value of port, does not matter connection will be created on port 3306 
    basicDataSource.setUrl("jdbc:mysql://localhost:8806/db"); 
    basicDataSource.setUsername("user"); 
    basicDataSource.setPassword("password"); 
} 

从这个代码,我期待着某些sshHost:22将在localhost:8806可用。

但我得到了connection = dataSource.getConnection();而不是connection = dataSource.getConnection();总是连接到数据库上localhost:3306

enter image description here

正如我刚才所说,我也尝试通过腻子连接 - 结果是相同的,通过代码连接忽略端口。

P.S.当我在IDEA的数据库工具连接到'localhost:8806'时,Putty的隧道才有效。

P.P.S.感谢@Cool建议现在我可以从代码中建立隧道。但dataSource继续忽略端口。

回答

1

您应该将“8806”转发到“3306”而不是“22”端口。 所以我现在不能测试,但你应该使用以下行

session.setPortForwardingL(8806, "sshHost", 3306); 

顺便说一句,你可以使用以下无需腻子等

ssh [email protected] -L 8806:localhost:3306 
+0

哦,我明白了我的错误代码,但现在不能尝试。 腻子隧道有什么问题? –

+0

它应该是L8806 sshHost:3306不是本地主机 – cool

+0

非常感谢,希望它会帮助我 –