【问题标题】:How to store multiple lines of command output to a variable using JSch如何使用 JSch 将多行命令输出存储到变量中
【发布时间】:2021-07-04 08:20:48
【问题描述】:

所以,我有一段很好的代码(我很难理解),它允许我向我的服务器发送命令,并得到一行响应。该代码有效,但我想从服务器返回多行。

主要类是:

JSch jSch = new JSch();
MyUserInfo ui = new MyUserInfo();
String Return = "Error";
try {
    String host = "Username@HostName";
    String user = host.substring(0, host.indexOf('@'));
    host = host.substring(host.indexOf('@') + 1);
    Session rebootsession = jSch.getSession(user, host, 22);
    rebootsession.setPassword(Password);
    rebootsession.setUserInfo(ui);
    rebootsession.connect();
    Channel channel = rebootsession.openChannel("exec");
    ((ChannelExec) channel).setCommand(Command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    channel.connect();
    byte[] tmp = new byte[1024];
    while (true) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0) break;
            Return = new String(tmp, 0, i);
        }
        if (channel.isClosed()) {
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    rebootsession.disconnect();
} catch (Exception e) {
    JOptionPane.showMessageDialog(null, e);
}
return Return;

我希望能够从头等舱返回多行。 任何帮助将不胜感激!

【问题讨论】:

  • 我不明白你想要什么?你能举个例子吗?
  • 下面的答案解决了这个问题,但是一个例子是当我使用 lshw 命令时,它只返回一行,而不是整个配置。还是谢谢!

标签: java linux jsch


【解决方案1】:

您必须将输出连接到 Return 变量,而不是在每次传递中覆盖它:

Return += new String(tmp, 0, i);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 2021-12-26
    • 2014-04-01
    • 2012-04-03
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多