Killing a process through sshj

只愿长相守 提交于 2019-12-04 07:23:13

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 :/

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

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.

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.

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