Trouble killing a process on windows

Tim Golden mail at timgolden.me.uk
Sun Jun 3 05:13:19 EDT 2007


Thomas Nelson wrote:

[... re Access Denied error on trying to TerminateProcess ...]

[Tim Golden]
>> I suppose you might have to adjust your token privs to include,
>> say the Debug priv. This is designed to let you take control
>> of any process (and terminate it, or whatever). If it looks
>> like you need to do that, post back and I -- or someone else --
>> can try to run up an example.

[Thomas Nelson]
> I Tried the PID method, and the Taskkill method, and neither worked.
> This is what I get for trying to work on a windows machine.  If you
> could explain how to add the debug privilege, that would be great.

OK, this being Windows security, there's a couple
of hoops to jump through, but nothing too bad.

<code>
import win32api
import win32security as sec

#
# This function is merely window-dressing
# to make it easier to see whether the
# code has worked or not.
#
def priv_status (hToken, priv):
   for p, status in sec.GetTokenInformation (
     hToken,
     sec.TokenPrivileges
   ):
     if p == priv:
       if status == 0:
         return "disabled"
       else:
         return "enabled"
   else:
     return "disabled"

process = win32api.GetCurrentProcess ()
token_access_flags = sec.TOKEN_ADJUST_PRIVILEGES | sec.TOKEN_QUERY
hToken = sec.OpenProcessToken (process, token_access_flags)
debug_priv = sec.LookupPrivilegeValue (None, sec.SE_DEBUG_NAME)

print "Debug is", priv_status (hToken, debug_priv)

privs = [(debug_priv, sec.SE_PRIVILEGE_ENABLED)]
sec.AdjustTokenPrivileges (hToken, 0, privs)

print "Debug is", priv_status (hToken, debug_priv)

</code>

> Just out of curiosity, is there a reason a python module like os
> couldn't have a universal terminateProcess type function, that works
> on all systems?  Something like os.listdir seems to work really well
> everywhere.  Maybe killing processes is too complicated for this?

Not to say that there could never be one, but I suspect
that the difference of APis and the number of corner
cases makes it a daunting task for maintenance. The
code would have to work on every platform Python works
on -- which is no small number -- and would have to be
maintained across the many and varied changes on each
of those platforms.

Still, if you think you're in with a chance, go ahead
and offer :)

Let us know if the DEBUG priv thing works or not.

TJG



More information about the Python-list mailing list