java后端代码通过Ansible执行shell命令,使远程机器执行可执行脚本等,执行完毕后出现一堆ssh进程且一直存在没有自动关闭。
而且当我执行得越多,ssh进程就会残留得越多,最终导致我的服务器资源不够用,项目崩溃。到底该怎么解决啊?
我有了解过其实Ansible是通过ssh来进行连接操作的,所以ssh的大量出现跟我代码用Ansible执行命令有关,但实际要怎么解决呢,求帮忙!
这是我Ansible执行命令的代码:
public AnsibleResult exec(String command) throws Exception {
AnsibleResult ansibleResult = new AnsibleResult();
Process process = null;
StringBuffer normalReader = new StringBuffer();
StringBuffer errorReader = new StringBuffer();
try {
String[] shellCommand = {"/bin/sh", "-c", command};
process = Runtime.getRuntime().exec(shellCommand);
logger.info("***************************************");
logger.info("ansible exec shell pid:" + process.pid());
logger.info("***************************************");
OutStream outPut = new OutStream(process.getInputStream(), normalReader);
OutStream error = new OutStream(process.getErrorStream(), errorReader);
error.start();
outPut.start();
//5分钟超时X`
int timeout = 5;
int exitValue = process.waitFor(timeout, TimeUnit.MINUTES) ? 0 : 1;
ansibleResult.setCommand(command);
ansibleResult.setStatusCode(exitValue);
logger.info("正确流:{}", normalReader);
logger.info("错误流:{}", errorReader);
ansibleResult.setNormalMsg(normalReader.toString());
ansibleResult.setErrMsg(normalReader.toString());
} catch (Exception e) {
logger.error("执行命令失败!命令:{}", command, e);
if (null != process) {
Stream<ProcessHandle> descendants = process.descendants();
descendants.forEach(c -> c.destroyForcibly());
process.destroyForcibly();
}
} finally {
if (null != process) {
Stream<ProcessHandle> descendants = process.descendants();
descendants.forEach(c -> c.destroyForcibly());
process.destroyForcibly();
}
}
return ansibleResult;
}
ps -ef 查看进程
而且随着我执行上述方法,ssh进程只会越来越多。
这段代码执行了很多对远程主机文件夹移动和执行.sh脚本的操作