【问题标题】:Java Jsch and expect : control an interactive program through SSHJava Jsch和expect:通过SSH控制交互程序
【发布时间】:2015-10-29 09:56:31
【问题描述】:

我正在尝试开发一个用于与某些程序交互的界面。 我有一台装有界面的 Windows 计算机,还有一台将启动程序的 Raspberry Pi。

我必须通过 SSH 使用它们,然后才能与之交互:

  • 从一些文本字段中,我获取程序的参数,然后启动它,连接到 SSH 会话。程序停留在等待状态“输入消息:”。
  • 然后用户必须能够在计算机的另一个文本字段中输入消息,才能在程序中使用此消息。这就是问题所在。

这是用于 2 个树莓之间的无线通信!

其实我通过任何Expect库(expectJ、expect4J、expectIt)启动程序都没有什么困难,但是之后总是无法输入消息。

架构是:

public SSH(String host, String user, String password) throws Exception {
    connection = new JSch();
    try {
        session = connection.getSession(user, host, 22);
        session.setPassword(password);
        connection.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        channel = session.openChannel("shell");
        channel.connect();
        expect = new ExpectBuilder()
                .withOutput(channel.getOutputStream())
                .withInputs(channel.getInputStream(), channel.getExtInputStream())
                .withEchoInput(System.out)
                .withEchoOutput(System.out)
                .withExceptionOnFailure()
                .build();
    } catch (JSchException e) {
        System.out.println(e.getMessage());
        throw new Exception("Error on session");
    }
}

public void exec(String prog) {
    try {
        expect.sendLine(prog);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public String send(String cmd){
    try {
        expect.sendLine(cmd);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

return "" 应该是程序结束时的确认。 但是 send() 总是失败并作为 linux 命令行输入数据......! 所以,我正在寻找一个解决方案,比如期望实例的“子期望”......就像这样:

SSH --
      |-./udp xxxxx
        -|"hello"
        -|"132"
      |-close()

有人有想法吗?

谢谢!

【问题讨论】:

  • 请分享您的发送代码,以便我们为您提供帮助
  • @aeldred 请不要编辑您的问题以包含答案或在标题中添加“已解决”。您可以通过填写页面底部的“答案”框来回答问题,包括您自己的问题。

标签: java swing expect jsch expectit


【解决方案1】:

Per @aeldred:我成功做到了!如果有人搜索同样的问题,是程序执行的调用导致通信失败,不得不用 ChannelExec 替换我的频道,我的 exec 方法变成了:

 public void exec(String prog) {
        try {
            channelExec.setCommand(prog);
            channelExec.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

【讨论】:

    猜你喜欢
    • 2017-10-21
    • 2016-04-30
    • 2013-12-31
    • 2013-05-04
    • 2013-07-28
    • 2015-05-05
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多