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

Viewed 485

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

2 Answers

Here's a skeleton for what you're looking for:

import psutil

pids = []
for p in psutil.process_iter():
    try: 
        name = p.name()
        if "firefox" in name.lower():
            pids.append(p.pid)
    except (psutil.NoSuchProcess, psutil.ZombieProcess):
        pass

connections = psutil.net_connections()

for con in connections: 
  if con.pid in pids:
    print (con)

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
Related