如何使用 WMI 通过 Python 获取进程所有者?

问题描述:

我尝试使用 WMI 获取有关进程所有者的一些信息.我试图运行这个脚本:

I tried to get some information about Process Owner, using WMI. I tried to run this script:

import win32com.client

process_wmi = set()
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")


process_list = objSWbemServices.ExecQuery("Select * from Win32_Process")
for process in process:
    owner = process.GetOwner
    if owner != 0:
        print('Access denied')
    else:
        print('process: ',process.Name, 'PID: ', process.ProcessId, 'Owner: ', owner)

当然,我得到 owner = 0(成功完成)

当我尝试调用 process.GetOwner() 时,出现此错误:TypeError: 'int' object is not callable

When I tried to call process.GetOwner(), I get this error: TypeError: 'int' object is not callable

如何使用这个方法而不出错?用什么参数或用什么标志?

How to use this method without errors? With what parameters or with what flags maybe?

我尝试实现并使用这种方法,此处,但我无法将代码转换为我的情况并获得流程所有者.=(

I try to actualize and use this method, here, but I can't convert code to my situation and get Process Owner. =(

或者可能有人知道另一种方法,如何获取有关进程所有者的信息.可能使用 WinApi 方法?

Or may be someone know another method, how to get information about process owner. May be with WinApi methods?

感谢您的帮助!

我建议使用 psutil 库.我使用的是 winapi 和 wmi,但它非常慢:( psutil 快得多,并且为您提供了一个方便的 API 来处理进程.

I would suggest using the psutil library. I was using the winapi, and wmi, but it's terribly slow :( psutil is much, much faster and gives you a convenient API for working with processes.

您可以像这样实现相同的目标:

You can achieve the same thing like this:

import psutil
for process in psutil.get_process_list():
    try:
        print('Process: %s, PID: %s, Owner: %s' % (process.name, process.pid,
                                                   process.username))
    except psutil.AccessDenied:
        print('Access denied!')

而且因为只有用户名才能让您拒绝访问,您可以在 except 中执行以下操作:

And because only the username can give you Access denied you can in except do:

except psutil.AccessDenied:
    print('Process: %s, PID: %s, Owner: DENIED' % (process.name, process.pid)

如果您只能使用 pywin32 和 wmi,那么这将起作用:

If you can use only pywin32 and wmi then this will work:

import wmi
for i in wmi.WMI().Win32_Process():
    print('%s, %s, %s' % (i.Name, i.ProcessId, i.GetOwner()[2]))