【问题标题】:How to use JSch with ProxyJump in .ssh/confg [duplicate]如何在 .ssh/config 中使用 JSch 和 ProxyJump [重复]
【发布时间】:2019-03-20 00:11:44
【问题描述】:

我在 ~/.ssh/config 下有配置文件包含:

Host jumbHost
   HostName x.domain.com

Host host1
   HostName y1.domain.com
   ProxyJump  jumbHost

我如何使用 JSch 通过 host1 隧道到 x.domain.com 服务器,以便执行命令?

注意:y1.domain.com 没有公共 IP

我尝试使用jsch.setConfigRepository(config_file_path),但似乎我需要设置更多配置或使用方法。

如果用例子来描述会非常有用。

编辑: 所以当我使用jsch.getSession(user,"host1"); 或类似的东西获得会话时,我可以 ssh 到 x.domain.com 服务器

提前致谢

【问题讨论】:

标签: java ssh jsch


【解决方案1】:

感谢 KevinOMartin Prikryl 提供有价值的提示和帮助

根据您的描述和链接,我能够应用所需的配置以使用 host1启用对 x.domain.com 的访问> 命名,然后在 y1.domain.com

上执行命令

为了记录,这就是我最终的结果

public class Main {
public static void main(String args[]) throws Exception {
    try {
        String user = "user_name";
        String host = "host1";
        String command = "hostname";

        JSch jsch = new JSch();
        ConfigRepository configRepository = OpenSSHConfig.parseFile(System.getProperty("user.home") + "/.ssh/config");
        jsch.setConfigRepository(configRepository);
        jsch.addIdentity(new File(System.getProperty("user.home") + "/.ssh/id_rsa").getAbsolutePath());

        Session sessionProxy = jsch.getSession(user,configRepository.getConfig(host).getValue("ProxyJump"),22);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        sessionProxy.setConfig(config);
        sessionProxy.connect();

        int assignedPort = sessionProxy.setPortForwardingL(0, configRepository.getConfig(host).getHostname(), 22);

        Session sessionTunnel = jsch.getSession(user, "127.0.0.1", assignedPort);
        sessionTunnel.connect();

        Channel channel = sessionTunnel.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        InputStream input = channel.getInputStream();
        channel.connect();

        try {
            InputStreamReader inputReader = new InputStreamReader(input);
            BufferedReader bufferedReader = new BufferedReader(inputReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(">>> output: " + line);
            }
            bufferedReader.close();
            inputReader.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        channel.disconnect();
        sessionTunnel.disconnect();
        sessionProxy.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
} 
}

【讨论】:

  • 请接受您的问题是重复的,而不是重复答案。
  • 是的,它是重复的,我只是把代码记录下来,谢谢
猜你喜欢
  • 2020-10-18
  • 2022-06-20
  • 2017-01-07
  • 2019-05-02
  • 2015-08-11
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多