简体   繁体   中英

How do I read Windows Registry file to check for values? [Python]

I am trying to perform auditing checks on Windows Registry file (.reg file, offline) and I am hoping that I can utilize Python to perform a check on the reg file.

For example (pseudo code):

#Configure registry policy processing: Do not apply during periodic background processing 

testloc = "C:\\Users\\test.reg"
datafile = open(testloc, "r")
read = datafile.read()

find(Software\Policies\Microsoft\Windows\Group Policy\{35378EAC-683F-11D2-A89A-00C04FBBCFA2})
check(NoBackgroundPolicy) #check if dword value is correct

if(dword == correct):
    print("correct")
else:
    print("wrong")

I have tried looking at _winreg but it seems like it does a check on a live system using Windows API. Another issue is the large .reg file size(~200MB).

How can I perform such a check using Python?

I don't know if there's a lib that can read .reg files specifically, but from what it looks like it's just an INI file with an extra version information at the top.

Here's an example of how you could use the configparser module for that. Some notes:

  • .reg files are encoded in utf16
  • Before giving the file to the ConfigParser , a readline will skip the version info (something like Windows Registry Editor Version 5.00 ). Otherwise it will result in a MissingSectionHeaderError .
  • The names of values include quotation marks, which means you need to add them explicitly when looking up the value in the key.

import configparser

testloc = "C:\\Users\\test.reg"

regdata = configparser.ConfigParser()
with open(testloc, "r", encoding="utf-16") as f:
    f.readline()  # skip version info in first line
    regdata.read_file(f)

key = regdata[r"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Group Policy\{35378EAC-683F-11D2-A89A-00C04FBBCFA2}"]
value = key['"NoBackgroundPolicy"']

print(value)

There may be drawbacks of doing it this way though, for example in how the values you obtain are formatted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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