如何读取JSch命令输出?
我有以下代码:
JSch jsch = new JSch();
jsch.setKnownHosts(dotSshDir + "/known_hosts");
jsch.addIdentity(dotSshDir + "/id_rsa");
Session session = jsch.getSession(userName, hostname, 22);
session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.setInputStream(null);
channel.setErrStream(System.err);
Reader reader = new InputStreamReader(channel.getInputStream());
char[] buf = new char[1024];
int numRead;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
result.append(readData);
buf = new char[1024];
}
它挂起试图从阅读器读取。我该如何解决这个问题?我该如何去追查正在发生的事情?
I have the following code:
JSch jsch = new JSch();
jsch.setKnownHosts(dotSshDir + "/known_hosts");
jsch.addIdentity(dotSshDir + "/id_rsa");
Session session = jsch.getSession(userName, hostname, 22);
session.connect();
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.setInputStream(null);
channel.setErrStream(System.err);
Reader reader = new InputStreamReader(channel.getInputStream());
char[] buf = new char[1024];
int numRead;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
result.append(readData);
buf = new char[1024];
}
It's hanging trying to read from the reader. How do I fix this? How do I go about hunting down what's happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在等待命令完成的同时,必须连续读取输出。否则,如果该命令产生足够的输出来填充输出缓冲区,该命令将挂起,等待缓冲区被消耗,这永远不会发生。所以你陷入了僵局。
以下示例连续读取 stdout 和 stderr,同时监视命令状态。它基于官方 JSch
exec.java
示例< /a> (仅添加 stderr 的读数)。如果您在
channel.connect();
之后添加while (!channel.isClosed()) {}
,您将看到具有足够大的i< /code> 在 shell
for
循环中(在我的环境中 10000 就足够了),循环永远不会结束。One has to read the output continuously, while waiting for the command to finish. Otherwise, if the command produces enough output to fill in an output buffer, the command will hang, waiting for the buffer to be consumed, what never happens. So you get a deadlock.
The following example reads both stdout and stderr continuously, while monitoring a command status. It is based on the official JSch
exec.java
example (just adds a reading of stderr).If you add
while (!channel.isClosed()) {}
after thechannel.connect();
, you will see that with a sufficiently largei
in the shellfor
loop (10000 is enough with in my environment), the loop never finishes.