Scroll through the entire record

Asked

Viewed 235 times

0

I wonder if there is a way I can go through the entire registry (keys and subkeys, do not need the value of them) of the operating system to find the name of a key in specific?

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

  • If you just want to make sure that a key exists, why go through the whole record? in any case, you can use the function EnumKey module Winreg to enumerate the keys.

  • I want to kind of do a search through the registry without having a predefined path. For example: find the key x across the registry.

  • Got it, do you want to find only the first occurrence or keep looking? maybe recursion is necessary in this case.

  • The key would happen to be the PATH?

1 answer

1

Python has a module to access the Windows registry. It comes together in the standard library, no need to import anything external.

import winreg

This module has a function that takes an HKEY and an index, and returns the HKEY key name on that index. If the index is invalid, it releases a Windowserror. Thus it is possible to get the name of all the immediate subchaves 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 entire record tree. It’s basically the pre-order browsing algorithm in some 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 enough to solve the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.