Reputation: 9720
I am trying to execute some shell commands using JSch on a remote machine. However, when that command runs and returns quickly (like ls
, my method returns, but when the command takes a while to run, and produces a lot of output (like service myservice stop; service myservice start
, where service is the name of some of the services i need to restart), my method gets stuck in the outer while(true)
loop, and I can't figure out why.
EDIT Turns out, it is not the time of the execution of the remote command, it is something else. I tried this method with a python script on the other end that just writes garbage for 10 minutes, and that returns normally.
Here is the code:
private String execCommand(String command) throws JSchException, IOException {
Channel channel = session.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;
System.out.print(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();
return new String(tmp,Charset.forName("UTF-8"));
}
I also tried using the .isEOF()
to check whether the remote output has finished, but that doesn't work either.
My current thought is to use some sentinel, e.g. the MD5 of the command to run to determine that the remote end is done (that is, running the command + "; echo \"" + md5(command) + "\""
, but that doesn't feel right.
Can anyone help me, please?
Upvotes: 0
Views: 1122
Reputation: 9720
To all those who may follow my footsteps: I ended up using the Ganymed-SSH-2 library instead of JSch. The approach in that library seems more logical, and everything works. At least, I haven't come run into the problems I had with JSch.
Upvotes: 0