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

How to forward remote port 3306 to local port in android programmatically with ssh and connect to mysql

我想将数据从 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.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;
}

答案很简单:setPortForwarding 必须使用 "localhost" 作为主机名,因为远程端口未在远程接口上打开并且您已经登录到远程主机。

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