我正在尝试用Java在远程服务器上执行四个命令。由于命令涉及导出,我将它们链接在一起成为一个命令:
rm -f nohup.out && export <a few similar commands> && nohup #here I execute a
startup script#>nohup.out >nohup.out 2>nohup.err </dev/null &
然后我想等一下(大约30秒)并解析nohup.out中的IP地址。我遇到的问题是程序挂起并且似乎没有断开连接 - 调试代码表明它在下面的代码块中的某处断开,因为它实际上确实成功执行了命令服务器端
如何成功关闭连接?
使用JSch的发送代码来自本网站上的一个赞成解决方案,如下所示。在此之后有一个从未到达的调试行。
((ChannelExec)channel).setCommand(command);
InputStream commandOutput = channel.getInputStream();
channel.connect();
int readByte = commandOutput.read();
while(readByte != 0xffffffff)
//while (true)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
}
答案 0 :(得分:0)
我遇到了类似的问题,我正在阅读其他类型的流(例如websockets)。大多数情况下,它是关于read()阻塞而不是对中断做出很好的反应。如果是这种情况,您可能需要强制关闭通道或swith到非阻塞(可能使用available()或类似的东西)。
更好的是,您可以指定所需的输出流,而不是进行轮询读取。
这是一个有效的例子:
executor = (ChannelExec) session.openChannel("exec");
executor.setPty(true);
executor.setCommand(script);
executor.setOutputStream(output);
executor.setErrStream(error);
executor.connect();
int errorStatus = -1;
for (int i = 0; !executor.isClosed(); i++) {
if (i > 0) {
long delayMs = (long) (200L * Math.pow(i, 2));
Thread.sleep(delayMs);
}
if ((errorStatus = executor.getExitStatus()) != -1) {
break;
}
}
LOGGER.debug("Output: {}", output.toString());
LOGGER.debug("Error: {}", error.toString());