java - 通过 Jsch 端口转发的 Java 套接字连接
问题描述
我正在尝试通过本地端口转发建立套接字连接。流程是:
Client --> 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 );
}
解决方案
您需要更改以下行
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();
}
推荐阅读
- python - css没有在webpy中加载
- android - 如何通过recyclerview中的所有视图进行重申?
- azure-service-fabric - Service Fabric 重新启动应用程序
- java - 是否可以在没有抽象方法的情况下执行接口?
- angular - kendo-angular-upload:500 服务器错误代码后未触发错误事件
- cakephp - 如何使用 CakePHP 3 TranslateBehavior 删除翻译
- r - 在 R 中使用字符向量命名行
- sharepoint - Exchange Web 服务错误 - 找不到自动发现服务
- r - 如何有效地检查数字向量是否在数据框定义的区间内
- jenkins - 这是否可以在不在集群上设置 Jenkins 的情况下使用 K8S 插件创建从站?