title: Steps to successfully impersonate as user in Python Windows
body: <p>I was digging through the net to find a way to impersonate my python code as my admin account.
  There were lot of common suggestion but all were missing the complete process so thought of sharing it.</p>
  
  <blockquote>
    <p>We need win32 dlls registered before we can communicate with windows api.</p>
  </blockquote>
  
  <p>In CMD.exe "pip install pywin32"</p>
  
  <blockquote>
    <p>After successful install we need to run "python Scripts/pywin32_postinstall.py -install" under sciprts folder.
    This will register all modules/dll for win32 api</p>
  </blockquote>
  
  <pre><code>
  import win32security, win32con, win32.win32api , win32 ,win32.win32security
  
  class Impersonate:
      def __init__(self, login, password):
          self.domain = 'domain'
          self.login = login
          self.password = password
  
      def logon(self):
          self.handle = win32.win32security.LogonUser(self.login, self.domain,self.password,win32con.LOGON32_LOGON_INTERACTIVE,win32con.LOGON32_PROVIDER_DEFAULT)
          win32.win32security.ImpersonateLoggedOnUser(self.handle)
  
      def logoff(self):
          win32security.RevertToSelf() # terminates impersonation
          self.handle.Close() # guarantees cleanup
  
  if __name__=='__main__':
      a = Impersonate('user_name','user_password')
  
      # Logging in
      a.logon()
  
      # Do whatever
      print(f"\n\t\tImprosonating: {win32.win32api.GetUserName()}")
  
      #Another way to call an Object
      Impersonate.logoff(a) # Logoff and Clean up
  </code></pre>
  
  <p>Refernce: 
  <a href="https://pypi.org/project/pywin32/" rel="nofollow noreferrer">https://pypi.org/project/pywin32/</a></p>
  
  <p>Thank you: mhammond</p>
  
  <p>*Not my code, learned from "Python Cookbook" :)</p>