Atreyu
Atreyu

Reputation: 33

Windows Registry access for Python script

I'm working on a Python 3.7 script that eventually will be a CLI program like reg.exe is. I'm aiming to include the ability to add, delete and query keys and subkeys. At this point, I can create a new Key and iterate through all keys within the specific path however; once I try to write a value to the new key I made, I get a WinError 5 - Access denied.

Is there a way I can include in the script a way to have access to write to the registry?

I'm still a beginner with Python and programming, I've had a look at documents but I cant figure this one out.

Any help will be greatly appreciated. My code soo far:

import winreg

reg_connection = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)

reg_key = winreg.OpenKey(reg_connection, r"SOFTWARE\Microsoft\\")

winreg.CreateKey(reg_key, "New Key")

for key in range(3000):
    try:
        show_sub_keys = winreg.EnumKey(reg_key, key)
        print(show_sub_keys)
    except WindosError:
        break

new_key_value = winreg.OpenKey(reg_connection, r"SOFTWARE\Microsoft\New Key")
winreg.SetValueEx(new_key_value, "New Value",0,winreg.REG_SZ, "This Value")
winreg.CloseKey(new_key_value)

Upvotes: 1

Views: 4361

Answers (1)

zett42
zett42

Reputation: 27756

new_key_value = winreg.OpenKey(reg_connection, r"SOFTWARE\Microsoft\New Key")

Here you do not specify an argument for the optional access parameter, so the call passes the default value of KEY_READ. Hence you can only read from the key, but not write.

You should pass an argument for the access parameter, that specifies the permissions you need:

new_key_value = winreg.OpenKey(reg_connection, r"SOFTWARE\Microsoft\New Key", 0, 
                               winreg.KEY_SET_VALUE)

For further details, see the winreg reference.

Upvotes: 1

Related Questions