Search code examples
pythonwindowsregistry

Reading HKEY CURRENT USER from the registry in Python, specifying the user


In my application I run subprocesses under several different user accounts. I need to be able to read some of the information written to the registry by these subprocesses. Each one is writing to HKEY_CURRENT_USER, and I know the user account name that they are running under.

In Python, how can I read values from HKEY_CURRENT_USER for a specific user? I assume I need to somehow load the registry values under the user's name, and then read them from there, but how?

edit: Just to make sure it's clear, my Python program is running as Administrator, and I have accounts "user1", "user2", and "user3", which each have information in their own HKEY_CURRENT_USER. As Administrator, how do I read user1's HKEY_CURRENT_USER data?


Solution

  • According to MSDN, HKEY_CURRENT_USER is a pointer to HKEY_USERS/SID of the current user. You can use pywin32 to look up the SID for an account name. Once you have this, you can use open and use the registry key with the _winreg module.

    import win32security
    import _winreg as winreg
    
    sid = win32security.LookupAccountName(None, user_name)[0]
    sidstr = win32security.ConvertSidToStringSid(sid)
    key = winreg.OpenKey(winreg.HKEY_USERS, sidstr)
    # do something with the key