I’m using Paramiko to tail -f a file on a remote server.
Previously, we were running this via ssh -t, but that proved flaky, and the -t caused issues with our remote scheduling system.
My question is how to kill tail when the script catches a SIGINT?
My script (based on Long-running ssh commands in python paramiko module (and how to end them))
#!/usr/bin/env python2
import paramiko
import select
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('someserver', username='victorhooi', password='blahblah')
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command("tail -f /home/victorhooi/macbeth.txt")
while True:
try:
rl, wl, xl = select.select([channel],[],[],0.0)
if len(rl) > 0:
# Must be stdout
print channel.recv(1024)
except KeyboardInterrupt:
print("Caught control-C")
client.close()
channel.close()
exit(0)
The script catches my Ctrl-C successfully, and ends. However, it leaves the tail -f process running on the remote system,.
Neither client.close() nor channel.close() seem to terminate it.
What command can I issue in the except block to kill it?
The remote server is running Solaris 10.
While not the most efficient method, this should work. After you CTRL+C; In the KeyboardInterrupt handler you could
exec_command("killall -u %s tail" % uname)like so:This would kill any open processes named
tail. That may cause issues though if you havetails open that you dont want to close, if thats the case you couldgrepaps, get the pid andkill -9it.First, set tail to read
nlines from end of file before following. setnto a unique nuber liketime.time(), since tail doesn’t care if that number is larger then the number of lines in the file, the large number fromtime.time()shouldnt cause issues and will be unique. Then grep for that unique number in theps: