July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: John Nielsen
You need to authenticate a thread temporarily as another principal on a Windows machine—for example, to make something run with the appropriate administrative rights.
On Unix, you can call setuid. On Windows, the
impersonation task is slightly more involved, but not terribly so:
import win32security, win32con
class Impersonate:
def _ _init_ _(self, login, password):
self.domain = 'bedrock'
self.login = login
self.password = password
def logon(self):
self.handle = win32security.LogonUser(self.login, self.domain,
self.password, win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT)
win32security.ImpersonateLoggedOnUser(self.handle)
def logoff(self):
win32security.RevertToSelf( ) # terminates impersonation
self.handle.Close( ) # guarantees cleanup
if __name__=='__main__':
a = Impersonate('barney', 'bambam')
try:
a.logon() # become the user
try:
# Do whatever you need to do, e.g.,:
print win32api.GetUserName() # show you're someone else
finally:
a.logoff() # Ensure return-to-normal no matter what
except:
print 'Exception:', sys.exc_type, sys.exc_valueSometimes it is convenient to authenticate a thread as another principal. For example, perhaps something should run temporarily with administrative rights. This is especially useful if you do not want the hassle of making a COM object or a service (which are other ways to solve the problem or, rather, work around it). On Windows, processes ...
Read now
Unlock full access