0

I writing a script to automatically kill processes that have a specific user name. I'm using wmi library to find all the process and os to kill processes. I need a way to find the user name of the process so that I can kill it.

Here's a snippet

import os
import wmi

c = wmi.WMI()

for process in c.Win32_Process():
    print(process.ProcessId, process.Name)


def terminate(processName):
    os.system('taskkill /IM "' + processName + '" /F')

enter image description here

Laspeed
  • 791
  • 1
  • 5
  • 27
  • Maybe inside the os.system command? In Linux I'd say `os.system('pkill ' + processName + ' -u ' + userName)` – Giovanni Tardini Jul 28 '22 at 09:06
  • What I need is, the code to find the user name of a process, not the command to kill. I already have a function for killing – Laspeed Jul 28 '22 at 09:19
  • 1
    you might want to take a look at [this answer](https://stackoverflow.com/a/49978652/9267296). It's not WMI based, but it does what you want... – Edo Akse Jul 28 '22 at 09:29
  • `process.GetOwner()` is what you want. It returns a tuple (Domain, ReturnValue, User). It's worth noting though that unless you're running with Administrator privileges it returns `(None, 2, None)` if the process is not yours. – GordonAitchJay Jul 28 '22 at 09:35
  • Yeah just use `psutil`. Is there any reason why not? – GordonAitchJay Jul 28 '22 at 09:36
  • `GetOwner` return codes here: https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/getowner-method-in-class-win32-process#return-value – GordonAitchJay Jul 28 '22 at 09:37
  • @GordonAitchJay GetOwner() gets the username for the pc not the process – Laspeed Jul 28 '22 at 09:38
  • psutil seems to be the way to go let me do some research on it – Laspeed Jul 28 '22 at 09:39
  • @Laspeed "GetOwner() gets the username for the pc not the process". What has lead you to believe that? The [documentation](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/getowner-method-in-class-win32-process) states: _The GetOwner WMI class method retrieves the user name and domain name under which the process is running._ – GordonAitchJay Jul 28 '22 at 09:42
  • @GordonAitchJay Yeah you're right I just went back to my task manager and scroll through and saw Admin in there along with other user name such as network service/local/system. What I actually wanna do is be find the network services and kill them. Unfortunately whenever I use GetOwner() the sole results I get are either `Admin` or `none` – Laspeed Jul 28 '22 at 09:45

0 Answers0