Working with Registry in Python

111 views Asked by At

I want to change value of a registry. I tried the following, but it is not working. I don't know what the problem is in my code!

KeyVal = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects\{B3D42F82-AE5B-4AE1-939C-E958D13732D2}Machine\Software\Policies\Microsoft\Windows\RemovableStorageDevices\{53f5630d-b6bf-11d0-94f2-00a0c91efb8b}\Deny_Execute'

try:
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,KeyVal,0, winreg.KEY_ALL_ACCESS)
    key = winreg.CreateKey(winreg.HKEY_CURRENT_USER,KeyVal )
    winreg.SetValueEx(key,"Deny_Execute",0,winreg.REG_DWORD,0)
    winreg.CloseKey(key)
except:
    pass
1

There are 1 answers

0
Jean-François Fabre On

first big issue is your anti-pattern:

try:
   <some code>
except:
    pass

so if any error occurs, you don't know the error. So you have to handle the exception properly, for instance by printing the error message

try:
   <some code>
except Exception as e:
    print(str(e))

the real problem you're facing here is that you have to run your script with elevated privileges (as administrator), since you're requesting write access to a system registry key.

But you cannot see the "access denied" error because of the bad way of catching all exceptions.