JSch multiple tunnels/jumphosts

廉价感情. 提交于 2019-11-29 12:46:29

Your ssh command is making use of an SSH client (another ssh) running on "jump box".

When you want to implement the same using Java, you have two options:

  1. Do the same in Java, i.e. use session to run ssh -L 3307:mysqlDB:3306 username@server on the "jump box".

    See Executing a command using JSch.

    Though, I do not think you should rely on ssh program for the second jump, for the same reason you use Java/JSch for the first jump (and not ssh program).

  2. Avoid using a separate ssh tool, and instead open the other SSH session locally via yet another forwarded port. You can actually do the same using recent versions of ssh, with -J (jump) switch (supported since OpenSSH 7.3):

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

    I prefer this approach.


To implement the latter approach:

  • You have to forward some local port to server:22, so that you can open SSH connection to the 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();
    
  • Then you forward another local port via server to MySQL port:

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

    Now you should be able to connect to localhost:mysqlPort using MySQL client.


Obligatory warning: Do not use StrictHostKeyChecking=no to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks.

For a correct (and secure) approach, see:
How to resolve Java UnknownHostKey, while using JSch SFTP library?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!