如何在.ssh / config [duplicate]中使用JSch和ProxyJump

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

我在〜/ .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个回答
0
投票

感谢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();
    }
} 
}
© www.soinside.com 2019 - 2024. All rights reserved.