I am trying to run a command on a remote Linux box from Java using JSch (SSH) API. The value of exitStatus
is -1
i.e.
int exitStatus = channelExec.getExitStatus()
What is the possible reason to get a negative value?
Note the documentation on getExitStatus().
The exit status will be -1 until the channel is closed.
API Description
Here is my code. It works fine.
public static Result sendCommand(String ip, Integer port, String userName, String password, String cmd) {
Session session = null;
ChannelExec channel = null;
Result result = null;
try {
JSch jsch = new JSch();
JSch.setConfig("StrictHostKeyChecking", "no");
session = jsch.getSession(userName, ip, port);
session.setPassword(password);
session.connect();
channel = (ChannelExec)session.openChannel("exec");
InputStream in = channel.getInputStream();
channel.setErrStream(System.err);
channel.setCommand(cmd);
channel.connect();
StringBuilder message = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null)
{
message.append(line).append("\n");
}
channel.disconnect();
while (!channel.isClosed()) {
}
result = new Result(channel.getExitStatus(),message.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
try {
session.disconnect();
} catch (Exception e) {
}
}
}
return result;
}
'-1' means that the exit status code has not been received yet from the remote sshd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With