通过sshj杀死进程

net*_*ain 5 java ssh 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();
    }
Run Code Online (Sandbox Code Playgroud)

编辑

还尝试发送所有可用信号.

            for(Signal s : Signal.values()){
                cmd.signal(s);
            }
Run Code Online (Sandbox Code Playgroud)

小智 5

分配一个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();
}
Run Code Online (Sandbox Code Playgroud)

当然,能够发送信号会更好,但即使OpenSSH服务器不支持它,也没有希望:/


net*_*ain 2

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