如何使用JSch将多行命令输出存储到变量中

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

所以,我有很多代码(我一直在努力理解),这使我可以向服务器发送命令,并获得一行响应。该代码有效,但我想从服务器返回多行。

主要类别是:

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;

我希望能够从第一堂课返回多行。任何帮助将不胜感激!

java linux jsch
1个回答
1
投票

您必须将输出连接到Return变量,而不是在每次通过时都覆盖它:

Return += new String(tmp, 0, i);
© www.soinside.com 2019 - 2024. All rights reserved.