【问题标题】:How to create a bot that simulate an SSH shell user interaction?如何创建一个模拟 SSH shell 用户交互的机器人?
【发布时间】:2014-11-23 23:27:25
【问题描述】:

我正在尝试实现一个机器人,它可以模拟在 Java 中的 ssh 控制台上写入/读取的用户。 我正在使用 JSCH 库来管理 ssh 连接。 这是我开始的代码:

JSch jsch = new JSch();
Session session = jsch.getSession(username, ipAddress, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect(connectionTimeoutInMillis);
Channel channel = session.openChannel("shell");
InputStream is = new InputStream();
OutputStream out= new OutputStream();
channel.setInputStream(is);
channel.setOutputStream(out);
channel.connect();
channel.disconnect();
is.close();
out.close();
session.disconnect();

显然代码中的InputStreamOutputStream 是错误的,我需要使用机器人可以用来发送字符串(命令行)和接收字符串(命令执行的结果)的东西,我应该使用什么类型的流来获得这个?

此外,我注意到,如果我发送命令并在许多情况下使用System.out 作为输出流,则输出为空,因为(我几乎可以肯定)Java 应用程序在命令执行产生之前终止结果。告诉 JSCH 通道侦听器“等到命令执行完成”然后继续的最佳做法是什么?我可以在命令执行后使用Thread.sleep(someTime),但出于显而易见的原因我不太喜欢它。

【问题讨论】:

    标签: java linux shell ssh jsch


    【解决方案1】:

    考虑使用第三方Expect-like Java 库来简化与远程 shell 的交互。您可以尝试以下一组不错的选项:

    您还可以查看我自己的开源项目,该项目是我不久前创建的,作为现有项目的继承者。它被称为ExpectIt。我的图书馆的优点在项目主页上都有说明。

    这是一个使用 JSch 与公共远程 SSH 服务交互的示例。在您的用例中采用它应该很容易。

        JSch jSch = new JSch();
        Session session = jSch.getSession("new", "sdf.org");
        session.connect();
        Channel channel = session.openChannel("shell");
    
        Expect expect = new ExpectBuilder()
                .withOutput(channel.getOutputStream())
                .withInputs(channel.getInputStream(), channel.getExtInputStream())
                .withErrorOnTimeout(true)
                .build();
        try {
            expect.expect(contains("[RETURN]"));
            expect.sendLine();
            String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1);
            System.out.println("Captured IP: " + ipAddress);
            expect.expect(contains("login:"));
            expect.sendLine("new");
            expect.expect(contains("(Y/N)"));
            expect.send("N");
            expect.expect(regexp(": $"));
            expect.send("\b");
            expect.expect(regexp("\\(y\\/n\\)"));
            expect.sendLine("y");
            expect.expect(contains("Would you like to sign the guestbook?"));
            expect.send("n");
            expect.expect(contains("[RETURN]"));
            expect.sendLine();
        } finally {
            session.close();
            ssh.close();
            expect.close();
        }
    

    这里是完整可行的example的链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 2019-07-10
      • 2018-11-29
      • 1970-01-01
      • 2014-07-01
      相关资源
      最近更新 更多