繁体   English   中英

如何使用Python观察Windows注册表的更改

[英]How to watch the Windows registry for changes with Python

我希望观察某个注册表项以进行更改,并在Python更改后立即执行一些自动操作,例如程序在启动期间更改注册表项,并且我希望在之后强制键到旧值。

以下示例代码将强制计算器以日期时间模板开始,而不管上次使用的模板如何。 它使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM