如何使用JSch将多行命令输出存储到变量 [英] How to store multiple lines of command output to a variable using JSch
本文介绍了如何使用JSch将多行命令输出存储到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我有很多代码(我一直在努力理解),这使我可以向服务器发送命令,并获得一行响应.该代码有效,但是我想从服务器返回多行.
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.
主要课程是:
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!
推荐答案
您必须将输出连接到Return
变量,而不是在每次通过时都覆盖它:
You have to concatenate the output to the Return
variable, instead of overwriting it in each pass:
Return += new String(tmp, 0, i);
这篇关于如何使用JSch将多行命令输出存储到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文