JSch多个隧道/ jumphosts

问题描述 投票:2回答:1

我不确定这是否是由于使用私钥而不是密码进行端口转发,但这是我正在尝试做的事情

enter image description here

我需要在3306将本地端口3308一直转发到我的SQL DB。

我可以在我当地的终端上一起运行这样的东西

ssh -L 3308:localhost:3307 username@jumpbox "ssh -L 3307:mysqlDB:3306 username@server"

或者在我的本地运行第一部分,然后在跳转框上运行第二部分。两者都工作正常,我可以连接到我的localhost:3308。

当我开始使用JSch时,问题出现了。这是我的代码

JSch jsch = new JSch();
jsch.addIdentity("~/.ssh/id_rsa");

Session session = jsch.getSession("username", "jumpbox");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();

int assinged_port = session.setPortForwardingL(3308, "localhost", 3307);
Session mysqlSession = jsch.getSession("username", "server", assinged_port);
mysqlSession.setConfig("StrictHostKeyChecking", "no");
mysqlSession.connect(); // Connection timed out here
mysqlSession.setPortForwardingL(3307, "mysqlDB", 3306);

第一个连接已完成,但第二个连接已超时。

线程“main”中的异常com.jcraft.jsch.JSchException:java.net.ConnectException:操作超时(连接超时)

我在这里用JSch或端口转发做错了吗?

java ssh jsch portforwarding ssh-tunnel
1个回答
2
投票

你的ssh命令正在使用在“跳转框”上运行的SSH客户端(另一个ssh)。

如果要使用Java实现相同的功能,可以使用以下两种方法:

  1. 在Java中也一样,即使用session在“跳转框”上运行ssh -L 3307:mysqlDB:3306 username@server。 见Executing a command using JSch。 虽然,我认为你不应该依赖ssh程序进行第二次跳跃,出于同样的原因你使用Java / JSch进行第一次跳跃(而不是ssh程序)。
  2. 避免使用单独的ssh工具,而是通过另一个转发端口在本地打开另一个SSH会话。实际上你可以使用ssh的最新版本和-J (jump) switch(从OpenSSH 7.3开始支持)来做同样的事情: ssh -L 3308:mysqlDB:3306 -J username@jumpbox username@server 我更喜欢这种方法。

实施后一种方法:

  • 您必须将一些本地端口转发到server:22,以便您可以打开与server的SSH连接: JSch jsch = new JSch(); jsch.addIdentity("~/.ssh/id_rsa"); Session jumpboxSession = jsch.getSession("username", "jumpbox"); jumpboxSession.connect(); int serverSshPort = jumpboxSession.setPortForwardingL(0, "server", 22); Session serverSession = jsch.getSession("username", "localhost", serverSshPort); serverSession.connect();
  • 然后通过server将另一个本地端口转发到MySQL端口: int mysqlPort = serverSession.setPortForwardingL(0, "mysqlDB", 3306); 现在您应该能够使用MySQL客户端连接到localhost:mysqlPort

强制警告:不要使用StrictHostKeyChecking=no盲目接受所有主机密钥。这是一个安全漏洞。你失去了对MITM attacks的保护。

有关正确(和安全)的方法,请参阅: How to resolve Java UnknownHostKey, while using JSch SFTP library?

© www.soinside.com 2019 - 2024. All rights reserved.