SHARE
TWEET

killall

DeaD_EyE Feb 17th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python3
  2.  
  3. """
  4. This programm kills all processes by given process name with SIGTERM
  5. """
  6.  
  7. import sys
  8. import signal
  9. import os
  10. from pathlib import Path
  11.  
  12.  
  13. def killall(name):
  14.     for path in Path('/proc').glob('*'):
  15.         if path.name.isdigit():
  16.             try:
  17.                 comm_path = path / 'comm'
  18.                 comm = comm_path.read_text().strip()
  19.                 if name == comm:
  20.                     pid = int(path.name)
  21.                     print('Killing process', path.name, file=sys.stdout)
  22.                     os.kill(pid, signal.SIGTERM)
  23.             except (PermissionError, FileNotFoundError):
  24.                 pass
  25.             except Exception as e:
  26.                 print('Got exception:', e, file=sys.stdout)
  27.                 return 1
  28.     return 0
  29.  
  30.  
  31. def main():
  32.     if not sys.stdin.isatty():
  33.         name = sys.stdin.read().strip()
  34.     elif len(sys.argv) != 2:
  35.         print(__doc__)
  36.         print(sys.argv[0], 'exact_process_name')
  37.         print('or')
  38.         print('echo procname |', sys.argv[0])
  39.         sys.exit(1)
  40.     else:
  41.         name = sys.argv[1]
  42.     return killall(name)
  43.  
  44.  
  45. if __name__ == '__main__':
  46.     sys.exit(main())
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top