代码之家  ›  专栏  ›  技术社区  ›  Fangming

JSch多隧道/跳线主机

  •  1
  • Fangming  · 技术社区  · 7 年前

    enter image description here

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

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

    或者在我的本地计算机上运行第一部分,然后在jumpbox上运行第二部分。两者都可以正常工作,我可以连接到我的本地主机:3308。

    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:操作超时(连接超时)

    1 回复  |  直到 7 年前
        1
  •  5
  •   Martin Prikryl    5 年前

    你的 ssh ssh )在“跳箱”上跑步。

    1. 在Java中也这样做,即使用 session 运行 ssh -L 3307:mysqlDB:3306 username@server 在“跳转框”上。

      Executing a command using JSch

      不过,我认为你不应该依靠 为第二次跳转编写程序,原因与第一次跳转使用Java/JSch(而不是 ssh 程序)。

    2. 避免使用单独的 工具,而是通过另一个转发端口本地打开另一个SSH会话。实际上,您可以使用最新版本的 具有 -J (jump) switch

      ssh -L 3308:mysqlDB:3306 -J username@jumpbox username@server
      

      另见 Does OpenSSH support multihop login?


    要实施后一种方法:

    • 您必须将一些本地端口转发到 server:22 ,以便您可以打开到的SSH连接 server :

      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();
      
    • 然后,通过以下方式转发另一个本地端口: 服务器

      int mysqlPort = serverSession.setPortForwardingL(0, "mysqlDB", 3306);
      

      localhost:mysqlPort 使用MySQL客户端。


    StrictHostKeyChecking=no 盲目接受所有主机密钥。这是一个安全缺陷。你失去了一种保护 MITM attacks .


    How to resolve Java UnknownHostKey, while using JSch SFTP library?