Go through the entire record

0

I would like to know if I can get through the whole registry (keys and subkeys, do not need the value of them) of the operating system to find the name of a specific key?

If yes, could someone tell me how to do it in python 3.x + or at least give me a way to do this?

    
asked by anonymous 29.05.2015 / 05:24

1 answer

1

Python has a module to access the Windows registry. It comes together in the default library, you do not have to import anything external.

import winreg

This module has a function that receives a HKEY and an index, and returns the name of the HKEY subkey at that index. If the index is invalid, it releases a WindowsError. Thus it is possible to get the name of all the immediate subkeys of a given HKEY.

def obter_subchaves_imediatas(hkey):
    i = 0

    try:
        while True:
            yield winreg.EnumKey(hkey, i)
            i += 1
    except WindowsError:
        pass

Now, using the above function, it is easy to write a routine that recursively navigates through the records tree. It's basically the pre-order navigation algorithm in any tree.

def navegar_arvore(nome_chave_raiz):
    hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, nome_chave_raiz)

    for nome_subchave in obter_subchaves_imediatas(hkey):
        nome_completo = f'{nome_chave_raiz}\{nome_subchave}'
        yield nome_completo
        yield from navegar_arvore(nome_completo)

A simple loop lets you get all paths from a certain root.

for chave in navegar_arvore('Control Panel'):
    print(chave)

There are several points that can be improved in this code, but what was shown here is sufficient to solve the problem.

    
13.07.2018 / 21:38