Java/JSch 中的 SSH 命令给出退出代码 -1

SSH command in Java/JSch giving exit code -1

我正在 Java 中使用 JSch 远程检查服务器的文件修改状态。除了输出,我还在检查退出代码。 虽然测试服务器 运行 正常并且退出代码为 0,但生产服务器抛出退出代码 -1。我如何获得有关此 -1 及其含义的更多详细信息。

这是我的代码,删除了敏感区域。
如何在最后一行 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();

getExitStatus returns -1,此时退出码还不知道。

您可能需要等待 Channel.isClosed before calling Channel.disconnect


在您的测试环境中,连接或服务器的速度可能足以在您阅读之前填充退出状态。而在生产服务器上则不是。一个简单的竞争条件。