JSch SSH 连接在初始化反向隧道时抛出 NPE

JSch SSH connection throws NPE when initializing reverse tunnel

当我向 com.jcraft.jsch.Session 对象添加反向隧道时,连接初始化失败并显示以下堆栈跟踪:

com.jcraft.jsch.JSchException: java.lang.NullPointerException
        at com.jcraft.jsch.Session._setPortForwardingR(Session.java:2165)
        at com.jcraft.jsch.Session.setPortForwardingR(Session.java:1937)
        at com.jcraft.jsch.Session.setPortForwardingR(Session.java:1883)
        at com.project.client.handlers.SshClientHandler.<init>(SshClientHandler.java:41)
        at com.project.client.pcConnection.init(SdConnection.java:30)
        at Sdclient.main(Unknown Source)
Caused by: java.lang.NullPointerException
        at com.jcraft.jsch.Packet.padding(Packet.java:58)
        at com.jcraft.jsch.Session.encode(Session.java:892)
        at com.jcraft.jsch.Session._write(Session.java:1362)
        at com.jcraft.jsch.Session.write(Session.java:1357)
        at com.jcraft.jsch.Session._setPortForwardingR(Session.java:2160)
        ... 5 more

这里有完整的代码

private static JSch sshConn = null;
private Session sshSession;
public SshClientHandler(int _sshLocalSp, int _sshRemoteSp) {

    JSch.setLogger(new JSCHLogger());
     sshConn = new JSch();
    try {
        createTemporarySshFiles();

        sshConn.setKnownHosts(GeneralMethods.getPreference(PcPreferencesEnum.SSH_KNOWN_HOSTS_FILE));
        sshConn.addIdentity(GeneralMethods.getPreference(PcPreferencesEnum.SSHC_PRIVATE_KEY_FILE), GeneralMethods.getPreference(PcPreferencesEnum.SSHC_PUBLIC_KEY_FILE), "".getBytes());

        sshSession = sshConn.getSession(GeneralMethods.getPropValue("pcclient.id"), "sshserver.project.com", 22);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(config);

        sshSession.setTimeout(15000);
        sshSession.setPassword("");
        //sshSession.setPortForwardingR("50000:localhost:22");
        sshSession.setPortForwardingR(50000, "127.0.0.1", 22);
        sshSession.connect();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
}

当我删除行

时,使用公钥身份验证成功建立连接
sshSession.setPortForwardingR(50000, "127.0.0.1", 22);

SSH用户有权连接到远程机器上的本地端口50000。这是 authorized_keys

的片段
no-pty,permitopen="localhost:50000",command="/bin/echo not-allowed-to-do-this",no-X11-forwarding ssh-rsa AAAA[...]

我来回切换 setPortForwardingR 的参数,例如,我在网上找到的一些文档使用远程机器作为第二个参数,一些使用本地主机,但没有成功。

在远程服务器上观察 auth.log 表明连接甚至没有启动。 NullPointerExceptionsetPortForwardingR 调用的实际行上被抛出。我确保我的本地 SSH 服务器在本地端口 22 上是 运行,我可以手动连接到它。我尝试了不同的端口(例如,连接到我的本地 MySQL 服务器),但它总是因相同的堆栈跟踪而失败。

我正在使用 jsch-0.1.52.jar

您必须仅在 .connect() 之后调用 .setPortForwardingR()

参见示例:
http://www.jcraft.com/jsch/examples/Daemon.java.html