Sahil Ali
Sahil Ali

Reputation: 342

SSH command in Java/JSch giving exit code -1

I am checking file modified status of a server remotely using JSch in Java. apart from the output, i am also checking exit code. While the test server is running fine and giving exit code as 0, the production server is throwing exit code -1. How do i get more details on this -1 and its meaning.

Here is my code, with sensitive areas removed.
How do I get more details on the last line getExitStatus.

JSch js=new JSch(); 
Session s = js.getSession(username, host, 22);
s.setPassword(password);

Properties ssconfig = new Properties();
ssconfig.put("StrictHostKeyChecking", "no");
s.setConfig(ssconfig);
s.connect();

Channel c = s.openChannel("exec");
ChannelExec ce = (ChannelExec) c;

ce.setCommand("cd <some file dir> && date && ls -ltr");
ce.setErrStream(System.err);

ce.connect();

/*
 * temporary test print
 */
BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
  System.out.println(line);
}

/*
 * end of temporary print
 */
ce.disconnect();
s.disconnect();

System.out.println("Exit code: " + ce.getExitStatus());

return ce.getExitStatus();

Upvotes: 0

Views: 2385

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202652

The getExitStatus returns -1, when the exit code is not known yet.

You may need to wait for Channel.isClosed before calling Channel.disconnect.


In your test environment, the connection or server may be quick enough to fill the exit status before you read it. While on production server it is not. A simple race condition.

Upvotes: 1

Related Questions