desu
desu

Reputation: 43

Find ports a program uses with python

I want to find the ports used by 'plugin-container.exe' so I can monitor what IP addresses interact with that program, The problem is there are two 'plugin-container.exe's. I use Firefox Developer Edition.

I already have the monitoring part down but I need to automate getting the ports some how. From what I've seen, getting them means knowing what PID the process is using, two processes = 2 PIDs. ;_;

I could add BOTH of them but there is a ton of traffic going though my browser and it kills my program when I put all 4 ports in manually.

Right now I'm using this to get the list, re.findall to filter the 'plugin-container.exe' in the list, I then use psutil to find what ports.

I feel like there is an easier way to do all of this.

import os, sys, win32api, re, psutil

tasklistrl = os.popen("tasklist").readlines()

tasklistr = os.popen("tasklist").read()

Upvotes: 0

Views: 1681

Answers (2)

desu
desu

Reputation: 43

I figured it out. There is another port but they are consecutive. Meh.

   process_name = "plugin-container.exe" 
    for proc in psutil.process_iter(): 
        process = psutil.Process(proc.pid)
        pname = process.name()
        #print pname
        if pname == process_name: 
            print(proc.pid)
            d = psutil.Process(int(proc.pid))
            print(d.name())
            print(d.memory_info())
            dec = input("Use this one?")
            if dec in ["yes","y","yep"]:
                con = d.connections(kind='udp4')
                break
    for connection in con:
                yourmom = connection.laddr[1]
    port1 = yourmom
    port2 = port1 + 1

Upvotes: 1

alexanderlukanin13
alexanderlukanin13

Reputation: 4715

If you want a nice way to find processes by executable name using psutil, then you should use process_iter and cmdline:

my_processes = [x for x in psutil.process_iter() if os.path.split(x.cmdline()[0])[1] == 'python']

(substitute 'python' with executable name you want)

Upvotes: 0

Related Questions