Killing a process through sshj

 ̄綄美尐妖づ 提交于 2019-12-06 03:56:10

问题


Im using sshj and im trying to tail a file, but my problem is that the remote process is never killed.

In the following example code you can see that i try to tail /var/log/syslog, and then i send a kill signal to the process. However after the application has stopped and i list out all the processes on the server, i can still see an active tail process.

Why will not this code kill the process? and what can i do to remedy that?

    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();
    }

EDIT

also tried sending all available signals.

            for(Signal s : Signal.values()){
                cmd.signal(s);
            }

回答1:


Allocating a PTY and sending a Ctrl+C character code did the trick for me:

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();
}

Of course, being able to send signals would be better, but if even the OpenSSH server does not support it, there's no hope there :/




回答2:


openssh doesn't support it https://bugzilla.mindrot.org/show_bug.cgi?id=1424

Just use cmd.close(), that should term the process as well




回答3:


This is most likely a problem with the ssh server implementation, as i have tried using two different ssh clients and getting the same result. My solution ended up being a client-side tail logic, instead of "tail -f" to prevent free roaming processes.




回答4:


Had a similar issue recently. In my specific case it was the OpenSSH issue mentioned by @shikhar.

My solution was to run start another session (sharing the connection) and run a kill command pgrep mycommand | xargs kill.



来源:https://stackoverflow.com/questions/7330692/killing-a-process-through-sshj

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!