通过sshj杀死进程

我使用sshj和我试图尾随文件,但我的问题是远程进程永远不会被杀死。

在下面的示例代码中,您可以看到我尝试tail / 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); } 

分配一个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服务器不支持它,也没有希望:/

openssh不支持它https://bugzilla.mindrot.org/show_bug.cgi?id=1424

只需使用cmd.close(),这也应该是该过程的术语

这很可能是ssh服务器实现的问题,因为我尝试使用两个不同的ssh客户端并获得相同的结果。 我的解决方案最终成为客户端尾部逻辑,而不是“tail -f”来阻止自由漫游过程。

最近有一个类似的问题。 在我的具体情况下,这是@shikhar提到的OpenSSH问题。

我的解决方案是运行另一个会话(共享连接)并运行kill命令pgrep mycommand | xargs kill pgrep mycommand | xargs kill