Search code examples
pythonpsutil

The name of the user who started the process


There are several running processes with the same name, (for example: notepad.exe) and there is a PID of these processes .

import psutil
PROCNAME = "notepad.exe"
for proc in psutil.process_iter():
    if proc.name() == PROCNAME:
        print(proc)

I need to find out which network or local user the processes were running under


Solution

  • From psutil documentation:

    >>> import psutil
    >>> for proc in psutil.process_iter(['pid', 'name', 'username']):
    ...     print(proc.info)
    ...
    {'name': 'systemd', 'pid': 1, 'username': 'root'}
    {'name': 'kthreadd', 'pid': 2, 'username': 'root'}
    {'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'}
    ...
    

    You can get the username by specifying it in the process_iter call. I believe this code should do what you want:

    import psutil
    PROCNAME = "notepad.exe"
    for proc in psutil.process_iter(['pid', 'name', 'username']):
        if proc.name() == PROCNAME:
            print(f"process:{proc} owner:{proc.username()}")