Recursively iterating through the Windows registry and getting the full path of a HKEY object

165 Views Asked by At

I would like to code a function that recursively iterates through the entire Windows registry and then prints any key names that match the key_matches variable.

Ideally, this function would return a list of all keys that match, along with their full path.

Current code:

import winreg

def scan_registry(key, subkey, key_matches):
    key = winreg.OpenKey(key, subkey)

    subkey_names = []

    for i in range(winreg.QueryInfoKey(key)[0]):
        subkey_names.append(winreg.EnumKey(key, i))

    for subkey_name in subkey_names:
        if subkey_name == key_matches:
            print("Found matching key in", subkey + "\\" + subkey_name)

        scan_registry(key, subkey_name, key_matches)


scan_registry(winreg.HKEY_CURRENT_USER, "", "PowerSettings")

Right now, when the function finds a match, it will just print "Found matching key in Power\PowerSettings"

How can I get it to print the full path, which is SOFTWARE\Policies\Power\PowerSettings? I cannot find a way to get the entire path from the main key object.

Alternatively, I have to find a way to save the previous path as the function recursively iterates. I tried for a few hours but still couldn't figure it out.

1

There are 1 best solutions below

0
trincot On

Instead of subkey you could pass the path so far, including that subkey at the end.

Code can look like this:

def scan_registry(key, path, key_matches):
    key = winreg.OpenKey(key, path.split("\\")[-1])

    subkey_names = []

    for i in range(winreg.QueryInfoKey(key)[0]):
        subkey_names.append(winreg.EnumKey(key, i))

    for subkey_name in subkey_names:
        childpath = path + "\\" + subkey_name
        if subkey_name == key_matches:
            print("Found matching key in", childpath)

        scan_registry(key, childpath, key_matches)