Search code examples
pythonregistrywinreg

Python winreg module access denied


Here is my code:

import winreg as wreg
key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters',wreg.KEY_ALL_ACCESS)
wreg.SetValueEx(key,"IPEnableRouter", 0, wreg.REG_DWORD, 1)

When i run this script, it says

PermissionError: [WinError 5] Access is Denied

How to change the value as 0 to 1 or 1 to 0?


Solution

  • Three things to try:

    1. Add an extra 0 to your parameters for the res. Currently you not setting the sam.

    2. Use the Registry Editor to change the permissions on the key to allow you as a user to have access.

    Regedit screenshot

    1. It is better to always request the minimum required access, so I would recommend you use wreg.KEY_SET_VALUE instead of wreg.KEY_ALL_ACCESS.

    So the script would be as follows:

    import _winreg as wreg
    
    key = wreg.OpenKey(wreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 0, wreg.KEY_SET_VALUE)
    wreg.SetValueEx(key, "IPEnableRouter", 1, wreg.REG_DWORD, 1)