Saturday, November 19, 2022

Windows Registry as Persistent Memory for Python Apps

I was trying to be creative by not using the traditional .ini file or a database to store application settings/configurations. Still, the windows registry is a common thing to do and is only for Windows OS but it sounds more complicated and a little bit hard to crack for the average user. It is equivalent of builtin flash memory in micro controllers which was used by SpaceHuhn in creating the nodemcu wifi packet sniffer.

Today, I created a simple program that reads/creates/modifies registry keys/values. So simple but very useful and sounds a little bit of old school but Windows Registry is definitely a good option for storing additional information that the application needs to work properly.

Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import winreg

REG_PATH = r"SOFTWARE\Zunz\HWID"

def set_reg(name, value):
    try:
        winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH)
        registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, 
                                       winreg.KEY_WRITE)
        winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
        winreg.CloseKey(registry_key)
        return True
    except WindowsError:
        return False

def get_reg(name):
    try:
        registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0,
                                       winreg.KEY_READ)
        value, regtype = winreg.QueryValueEx(registry_key, name)
        winreg.CloseKey(registry_key)
        return value
    except WindowsError:
        return None
print (get_reg('GUID'))

#Set Value 1/20 (will just write the value to reg, the changed mouse val requires a win re-log to apply*)
set_reg('EXPDAT', str(1102022))

No comments:

Post a Comment