I was messing around with ssh and decided to write a python program that scans for any connections that aren't from the system, then terminates them. It works well for many connections from my iMac to my MacBook. A more in-depth explanation of the program is written at the top of the code. I'd appreciate feedback on any nitpicks you can find, since I threw this together in about thirty minutes. Any and all feedback is appreciated and considered.


""" Import Statements """
import os
import subprocess
import time


Objective: Scan all connections to this computer, every two seconds, and if any are not
system, as in not `console` or `s000`, find the PID associated with the connection,
then terminate the connection with `kill -9 ...`


def format_pid(text):
    Formats the output to only include PIDS that are not from the system
    ids = text.split("\n")
    all_ids = []
    del ids[0] #removes uptime stuff
    for line in ids:
        pid = line[:13]
        if pid[12:] != '0':
    return all_ids

def get_pids():
    """ Returns all users logged into the computer """
    return format_pid(subprocess.Popen(['ps'], stdout=subprocess.PIPE).communicate()[0])

def kill():
    """ Terminates all processes that are not system """
    processes = get_pids()
    for process in processes:
        if process: # Makes sure process isn't null/empty
            os.system('kill -9 ' + process)
            print("KILLED CONNECTION PROCESS: " + process)


if __name__ == '__main__':
  • \$\begingroup\$ No time for a proper review, but you may be interested in psutil. \$\endgroup\$ Jul 16, 2019 at 9:12

1 Answer 1


Replace magic numbers like 13 there line[:13] with constansts. IMHO:

  • rename ids to lines
  • all_ids to ids
  • processes to pids

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.