Killing processes with PSUTIL

左心房为你撑大大i 提交于 2019-12-12 11:12:19

问题


I'm looking to write some code that will kill off a process based on it's name and who owns it. This works fine on Windows XP but when I come to run the same code on Windows 7 I get Access Denied errors when trying to get the username of the process.

Is there an easier way to kill a process that will work on XP and Win7?

The check to see if the process is owned by the 'SYSTEM' is actually needed so I can check when the process has user processes are finished, as the SYSTEM process remains, and I'm not concerned with this one.

Thanks.

PROCNAME = 'python.exe'
for proc in psutil.process_iter():
  if proc.name == PROCNAME:
    p = psutil.Process(proc.pid)

    if not 'SYSTEM' in p.username:
      proc.kill()

回答1:


If you don't have the privilege to kill a process with PSUTIL, you're not going to have it with anything else. The first thing that comes to mind is, obviously, UAC, which appeared exactly between XP and Windows 7. Which implies that your PSUTIL must run from an elevated prompt, not surprising. Add a manifest to request elevation.




回答2:


the problem is some of the processes does not have names, and therefor you get the error.

If you put that in a try block it will work:

PROCNAME = 'python.exe'
for proc in psutil.process_iter():
  try:
      if proc.name == PROCNAME:
      p = psutil.Process(proc.pid)

      etc..
  except:
    pass



回答3:


This is just a guess, but maybe UAC is preventing Python from having administrator privileges. Try executing Python as administrator using the "run as administrator" thingy on Win 7 (I don't remember where it is exactly, but it probably involves launching a terminal as administrator, which can be done from the Start Menu, and then executing your Python script from there).




回答4:


Starting october 2010 (see issue 114), username is obtained using a C function call (see get_process_username in the source)

This means it suffers from the problem described in this previous stackoverflow question

Basically you can catch the AccessDenied exception and assume the user is either 'SYSTEM' or 'LOCAL SERVICE'

Edit: From what I see there is also a bug in Python that causes many more AccessDenied errors than there should have been. The SetSeDebug function from psutil calls RevertToSelf at the end, practically reverting all the changes it has done.



来源:https://stackoverflow.com/questions/12051485/killing-processes-with-psutil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!