如何使用ssh以编程方式将远程端口3306转发到android中的本地端口并连接到mysql

时间:2017-09-07 09:51:41

标签: java android ssh jsch mysql-connector

我想安全地将数据从android SQLite数据库传输到远程mysql数据库。由于我无法以编程方式设置VPN,因此我希望通过ssh隧道传输数据。我试过jkraft.jsch。转发运行没有错误,但是当我连接mysql-connector时 与

conexionMySQL =  DriverManager.getConnection("jdbc:mysql://localhost:53009/",user, password);

我收到以下错误:

java.sql.SQLException: Communication link failure: java.io.EOFException, underlying cause: null

** BEGIN NESTED EXCEPTION ** 

java.io.EOFException

STACKTRACE:

java.io.EOFException
    at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1395)
    at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:1414)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:625)
    at com.mysql.jdbc.Connection.createNewIO(Connection.java:1808)
    at com.mysql.jdbc.Connection.<init>(Connection.java:452)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
    at java.sql.DriverManager.getConnection(DriverManager.java:179)
    at java.sql.DriverManager.getConnection(DriverManager.java:213)
    at de.damian.android.common.Mysql$2.run(Mysql.java:151)
    at java.lang.Thread.run(Thread.java:841)


** END NESTED EXCEPTION **

代码是:

public int connectSSH(int rport)
{

// 
    int assigned_port;
    final int local_port = 53009;

// Remote host and port
    final int remote_port = rport;
    final String remote_host = "test.test.org";

    try
    {
        jsch = new JSch();

// Create SSH session. Port 22 is your SSH port which.   
// is open in your firewall setup.
        session = jsch.getSession("xxx", remote_host, 22);
        session.setPassword("xxxxxx");

// Additional SSH options. See your ssh_config manual for.    
// more options. Set options according to your requirements.
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        config.put("Compression", "yes");
        config.put("ConnectionAttempts", "2");

        session.setConfig(config);

// Connect
        session.connect();

// Create the tunnel through port forwarding. 
// This is basically instructing jsch session to send 
// data received from local_port in the local machine to 
// remote_port of the remote_host.  
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as.  
// local_port.

        assigned_port = session.setPortForwardingL(local_port,
                remote_host, remote_port);

    }
    catch (JSchException e)
    {
        Log.e(Level.SEVERE.toString(), e.getMessage(), e);
        return 0;
    }


    if (assigned_port == 0)
    {
        Log.e(Level.SEVERE.toString(), "Port forwarding failed !");
        return 0;
    }
    return assigned_port;
}

1 个答案:

答案 0 :(得分:1)

答案很简单:setPortForwarding必须使用&#34; localhost&#34;作为远程接口上没有打开远程端口的主机名,并且您已经在远程主机中登录。

assigned_port = session.setPortForwardingL(local_port,
            "localhost", remote_port);