通过sshj杀死一个进程
我使用sshj和即时尝试尾部文件,但我的问题是远程进程永远不会被杀死。通过sshj杀死一个进程
在下面的示例代码中,您可以看到我尝试尾部/ var/log/syslog,然后向该进程发送kill信号。但是,在应用程序停止并列出服务器上的所有进程之后,我仍然可以看到活动的尾部进程。
为什么这段代码不会杀死进程?我能做些什么来补救呢?
SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier(new PromiscuousVerifier());
try {
ssh.connect("localhost");
ssh.authPassword("xxx", "xxx");
final Session session = ssh.startSession();
try {
final Command cmd = session.exec("tail -f /var/log/syslog");
cmd.signal(Signal.KILL);
System.out.println("\n** exit status: " + cmd.getExitStatus());
} catch (IOException e) {
e.printStackTrace();
}finally{
session.close();
}
} finally{
ssh.disconnect();
}
编辑
还试图将所有可用的信号。
for(Signal s : Signal.values()){
cmd.signal(s);
}
这是最有可能与SSH服务器的实现问题,因为我曾尝试使用两个不同的SSH客户端,并获得相同的结果。我的解决方案最终成为客户端尾部逻辑,而不是“tail -f”来防止漫游过程。
OpenSSH不会支持它https://bugzilla.mindrot.org/show_bug.cgi?id=1424
只需使用cmd.close(),应该称之为进程以及
首先,我不使用openssh ...并且cmd.close()不会终止进程。看来,日志状态'net.schmizz.sshj.connection.channel.AbstractChannel sendClose 信息:发送close'并保持挂在此直到发生超时异常。 – netbrain
最近有类似问题。在我的具体情况下,这是@shikhar提到的OpenSSH问题。
我的解决方案是运行启动另一个会话(共享连接)并运行kill命令pgrep mycommand | xargs kill
。
分配一个PTY和发送Ctrl + C键的字符代码的伎俩对我来说:
final Session session = ssh.startSession();
session.allocateDefaultPTY();
try {
final Command cmd = session.exec("tail -f /var/log/syslog");
// Send Ctrl+C (character code is 0x03):
cmd.getOutputStream().write(3);
cmd.getOutputStream().flush();
// Wait some time for the process to exit:
cmd.join(1, TimeUnit.SECONDS);
// If no exception has been raised yet, then the process has exited
// (but the exit status can still be null if the process has been killed).
System.out.println("\n** exit status: " + cmd.getExitStatus());
} catch (IOException e) {
e.printStackTrace();
}finally{
session.close();
}
当然,能够发送信号会更好,但如果连OpenSSH服务器不支持它,那里没有希望:/
你救了我的命。非常感谢。 – Umut
我正在使用这个[coreutil的超时](https://www.gnu.org/software/coreutils/manual/html_node/timeout-invocation.html) – TheConstructor
你真的在程序的输出中看到'** exit status:'行吗? –
是的,**退出状态:空。 – netbrain
你可以尝试使用另一个信号,例如'TERM'(kill命令行实用程序使用的默认值)? –