Search code examples
pythonportpid

Getting all PID Id's and Ports being Listened to with Python


I'm currently learning some python and I was just wondering what is the best way to get a list of all the PID Id's of say Firefox and then displaying all the port numbers it is listening to. I am trying to replicate the image below and yet I can't seem to figure it out. Sorry in advance but I currently do not have any code atm as I've been testing and trying code that I have googled and found to no success.

enter image description here


Solution

  • Use the package psutil

    pip install psutil

    Now for your desired output, iterate over all process and find the one with 'firefox' in its name

    import psutil
    for proc in psutil.process_iter():
        try:
            processName = proc.name()
            if "firefox" in processName:
                processID = proc.pid
                print(processName , ' ::: ', processID)
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass