遍历指定的注册表子项

时间:2018-12-17 04:10:29

标签: python-3.x iteration registry

我正在用Python 3开发Windows注册表编辑器。

目前,我在CURRENT_USER配置单元中查询SOFTWARE密钥的功能正在输出所需的内容,我正在寻找一个用户指定他们要查询的子项,例如Python子项,并对其进行迭代,但无法正常工作这个。

到目前为止,我的代码:

def query_registry():
    registry_path = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    registry_key = winreg.OpenKey(registry_path, r"SOFTWARE\\", 0, winreg.KEY_READ)

    for i in range(200):
        try:
            subkey_name = winreg.EnumKey(registry_key, i)
            print(i, "-", subkey_name)
        except:
            print("Number of Directories --> %s" %i + "\n")
            break

输出:

enter image description here

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

使query_registry()函数更具通用性,以便递归调用自身,例如如下(很抱歉 pythonish 代码太少了):

def query_registry( sargpath, sargxst):
    print(sargpath)
    iargxst = int( sargxst)
    registry_path = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
    registry_key  = winreg.OpenKey(registry_path, sargpath, 0, winreg.KEY_READ)
    info_key      = winreg.QueryInfoKey(registry_key)
    if ( iargxst < 0 ):
        for i in range(info_key[0]):
            subkey_name = winreg.EnumKey(registry_key, i)
            print(i, "-", subkey_name)
        print("Number of Directories --> %s\n" %(info_key[0]))
        ###
        if ( info_key[0] > 0 ):
            x = input('Enter subkey number (-1 to end): ')
            if ( int(x) in range(info_key[0]) ):
                subkey_name = winreg.EnumKey(registry_key, int(x))
                query_registry( sargpath + '\\' + subkey_name , -1 )
            else:
                exit()
    else:
        subkey_name = winreg.EnumKey(registry_key, iargxst)
        query_registry( sargpath + '\\' + subkey_name ,-1 )

### main ###
import sys
import winreg
query_registry(sys.argv[1],sys.argv[2])

结果示例:

==> D:\bat\SO\53808855.py "software" 19
software
software\Google
0 - Chrome
1 - Common
2 - Software Removal Tool
3 - Update
Number of Directories --> 4

Enter subkey number (-1 to end): 0
software\Google\Chrome
0 - BLBeacon
1 - BLFinchList
2 - BrowserCrashDumpAttempts
3 - BrowserExitCodes
4 - Extensions
5 - NativeMessagingHosts
6 - PreferenceMACs
7 - StabilityMetrics
8 - ThirdParty
Number of Directories --> 9

Enter subkey number (-1 to end): 6
software\Google\Chrome\PreferenceMACs
0 - Default
1 - Guest Profile
2 - Profile 2
3 - Profile 3
4 - System Profile
Number of Directories --> 5

Enter subkey number (-1 to end): -1

==>