通过 Jsch 端口转发的 Java 套接字连接

我正在尝试通过本地端口转发建立套接字连接。流程是:

客户端 --> SSHhost --> TargetHost


试图通过端口转发来实现这一点,但不断收到 IllegalStateException: Can't connect to rHost 错误。

我测试过远程主机确实直接接受连接,我的用例是通过 SSHhost 连接。


不确定哪里出了问题,或者我愿意接受不同的方法或建议?谢谢。


 try {

        jsch.addIdentity(privateKeyPath);

        session = jsch.getSession(username, hostL, port);

        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");

        java.util.Properties config = new java.util.Properties();

        session.setConfig(config);

    } catch (JSchException e) {

        throw new RuntimeException("Failed to create Jsch Session object.", e);

    }


    try {

        session.connect();


        session.setPortForwardingL(8080, rHost, rPort);

        try (Socket s = new Socket()) {

            s.connect(new InetSocketAddress(rHost, 8080), timeout);

        } catch (Exception e) {

            String errText = String.format("Can't connect to rHost")

            throw new IllegalStateException(errText);

        }


        session.disconnect();

    } catch (JSchException e) {

        throw new RuntimeException("Error durring session connection );

    }


撒科打诨
浏览 257回答 1
1回答

紫衣仙女

您需要更改以下行s.connect(new InetSocketAddress(rHost, 8080), timeout);到s.connect(new InetSocketAddress("localhost", 8080), timeout);因为你在使用该方法时实际上已经将本地主机端口 8080 映射到远程主机端口session.setPortForwardingL(8080, rHost, rPort);你可以试试这段代码try {            jsch.addIdentity(privateKeyPath);            session = jsch.getSession(username, hostL, port);            session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");            session.setConfig("StrictHostKeyChecking", "no");            session.connect();            session.setPortForwardingL(8080, rHost, rPort);            Socket s = new Socket();            s.connect(new InetSocketAddress("localhost", 8080), timeout);            session.disconnect();        } catch (JSchException e) {            e.printStackTrace();        } catch (Exception e) {            e.printStackTrace();        }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java