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);
}
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
.
来源:https://stackoverflow.com/questions/7330692/killing-a-process-through-sshj