问题
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