如何使用Python监视Windows注册表的更改

Oli*_*and 5 python registry winapi pywin32

我想查看某个注册表项的更改,并在使用Python更改后立即执行一些自动操作,例如,程序在启动过程中更改了注册表项,我想在此后立即将其强制为旧值。

Oli*_*and 4

以下示例代码将强制计算器从日期时间模板开始,无论上次使用的模板如何。它使用Python for Windows 扩展,提供了一种非常快速的方法来访问大多数 Windows 内部并自动化 COM 感知应用程序:

import win32api
import win32con
import logging 
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s', filename='watchRegistry.log')
log = logging.getLogger()

hiveToWatch = win32con.HKEY_CURRENT_USER
keyToWatch = r'Software\Microsoft\Calc'

values = {(hiveToWatch, keyToWatch, 'DateTime'): (win32con.REG_DWORD, 1),
          (hiveToWatch, keyToWatch, 'Templates'): (win32con.REG_DWORD, 0),
          (hiveToWatch, keyToWatch, 'UnitConv'): (win32con.REG_DWORD, 0)}

while True:

    for (hive, key, valueName), (valueType, value) in values.items():
        handleWithSetRights = win32api.RegOpenKeyEx(hive, key, 0, win32con.KEY_SET_VALUE)
        log.info(r'Setting %s\%s\%s = %s' % (hive, key, valueName, value))
        win32api.RegSetValueEx(handleWithSetRights, valueName, 0, valueType, value)
        win32api.RegCloseKey(handleWithSetRights)

    # Open and close the handle here as otherwise the set operation above will trigger a further round
    handleToBeWatched = win32api.RegOpenKeyEx(hiveToWatch, keyToWatch, 0, win32con.KEY_NOTIFY)
    win32api.RegNotifyChangeKeyValue(handleToBeWatched, False, win32api.REG_NOTIFY_CHANGE_LAST_SET, None, False)
    win32api.RegCloseKey(handleToBeWatched)
Run Code Online (Sandbox Code Playgroud)