Skip to content

Instantly share code, notes, and snippets.

@lenisko
Created October 10, 2017 23:04
Show Gist options
  • Save lenisko/1b7eea1c5466a76fb51537931932a3a2 to your computer and use it in GitHub Desktop.
Save lenisko/1b7eea1c5466a76fb51537931932a3a2 to your computer and use it in GitHub Desktop.
Simple python script used to kill not active pts sessions
#!/usr/bin/python
"""
Author: @lenisko
Simple python script used to kill not active pts sessions.
"""
import re
import subprocess
def parse_who():
p = subprocess.Popen(["who", "-m"], stdout=subprocess.PIPE)
p = p.stdout.read().decode("utf-8")
if not p:
raise Exception('Executing `who -m` failed')
r = re.search('(\w+).*pts/(\d+)', p)
if not r:
raise Exception('Can\'t parse `who -m` output')
user = r.group(1)
pts = r.group(2)
return user, pts
def parse_ps():
p = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE)
p = [i.decode("utf-8") for i in p.stdout.readlines()]
if not p:
raise Exception('Executing `ps aux` failed')
return p
def find_pts(user, ps_lines):
output = []
for line in ps_lines:
line = line
if user + '@pts' in line:
output.append(line)
return output
def pids_to_kill(active_pts, pts_output):
lines = []
for line in pts_output:
if 'pts/' + active_pts not in line:
lines.append(line)
pids = []
for line in lines:
pids.append(line.split()[1])
return pids
def kill_pids(pids):
for pid in pids:
subprocess.call(["kill", pid])
def main():
user, active_pts = parse_who()
ps_output = parse_ps()
pts_output = find_pts(user, ps_output)
pids = pids_to_kill(active_pts, pts_output)
if not pids:
print('Nothing to kill')
return
kill_pids(pids)
print('Killed!')
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment