How to store multiple lines of command output to a variable using JSch

安稳与你 提交于 2021-02-19 05:30:30

问题


So, I have a nice bit of code (that I'm struggling to understand), that allows me to send a command to my server, and get one line of response. The code works, but I would like to get multiple lines back from the server.

The main class is:

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;

I would like to be able to return multiple lines from the first class. Any help would be greatly appreciated!


回答1:


You have to concatenate the output to the Return variable, instead of overwriting it in each pass:

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


来源:https://stackoverflow.com/questions/41983638/how-to-store-multiple-lines-of-command-output-to-a-variable-using-jsch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!