title: Run program as different user on Windows (not admin) within a Python script
body: <p>With the following code:</p>
  
  <pre><code>class ImpersonateWin32Sec(object):
  
      def __init__(self, domain, username, password):
          self.username = username
          self.password = password
          self.domain = domain
          self.handle = None
  
      def __enter__(self):
          self.handle = win32security.LogonUser(self.username, self.domain, self.password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT)
          win32security.ImpersonateLoggedOnUser(self.handle)
  
      def __exit__(self, *args):
          win32security.RevertToSelf()
          self.handle.Close()
  
  with ImpersonateWin32Sec("domain", "altuser", "password"):
      prc = subprocess.Popen(cmdLine, cwd = "C:\\Temp", stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = env, shell = shell, creationflags = CREATE_NO_WINDOW)
      stdOut, stdErr = prc.communicate(timeout = 60)
  </code></pre>
  
  <p>I'm trying to run a program as a different user. It seems to work only partially, because some commands fail. The following 3 commands show that some parts of the environment are still for the original user:</p>
  
  <pre><code>os.getlogin() # altuser
  getpass.getuser() # origuser   --&gt; WRONG!!!
  win32api.GetUserName() # altuser
  </code></pre>
  
  <p>What is missing/wrong with my code? I've found some information that ImpersonateLoggedOnUser creates an impersonate token for the user, instead of a primary token? Could this be the problem? If yes how can I get a primary token? A code example would be very appreciated.</p>
  
  <p>Regards, Martin</p>