Mason Browne
Mason Browne

Reputation: 39

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

Upvotes: 2

Views: 1110

Answers (2)

Roy2012
Roy2012

Reputation: 12533

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)

Upvotes: 3

Rupesh
Rupesh

Reputation: 538

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

Upvotes: 1

Related Questions