Python – Search registry key

Posted: October 21, 2019 in Scripts, Windows Server

This function will print registry value for specific key, in this case HPATH value

import _winreg

def getPath():
    # Open the key and return the handle object.
    hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
    # Read the value.                      
    result = _winreg.QueryValueEx(hKey, "MachineId")
    # Close the handle object.
    result = result[0]
    return result

Another solution:

def regkey_value(path, name="", start_key = None):
    if isinstance(path, str):
        path = path.split("\\")
    if start_key is None:
        start_key = getattr(_winreg, path[0])
        return regkey_value(path[1:], name, start_key)
        subkey = path.pop(0)
    with _winreg.OpenKey(start_key, subkey) as handle:
        assert handle
        if path:
            return regkey_value(path, name, handle)
            desc, i = None, 0
            while not desc or desc[0] != name:
                desc = _winreg.EnumValue(handle, i)
                i += 1
            return desc[1]

posread = regkey_value(r"HKEY_LOCAL_MACHINE\COMODO", "MachineId")

3rd way:

import _winreg

reg_connection = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)

key_value = _winreg.OpenKey(reg_connection, r"COMODO")

print _winreg.QueryValueEx(key_value, "MachineId")[0]

Reading registry keys from x64 versions of Windows using x86 Python installation:

import _winreg

def get_path(name):
        registry_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\\COMODO', 0, (_winreg.KEY_WOW64_64KEY + _winreg.KEY_READ))
        value = _winreg.QueryValueEx(registry_key, "MachineId")[0]     
        return value
    except WindowsError:
        return None

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s