Killing processes with PSUTIL

后端 未结 5 1465
陌清茗
陌清茗 2021-01-12 07:58

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 Windo

相关标签:
5条回答
  • 2021-01-12 08:24

    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.

    0 讨论(0)
  • 2021-01-12 08:24

    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.

    0 讨论(0)
  • 2021-01-12 08:24

    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
    
    0 讨论(0)
  • 2021-01-12 08:32

    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).

    0 讨论(0)
  • 2021-01-12 08:42

    In case psutil does not work, you can always try using taskkill through os.system (command prompt) Example to kill all excel instances:

    import os
    os.system("""taskkill /f /im excel.exe""")
    
    0 讨论(0)
提交回复
热议问题