0

For example, I want to remove the whole path HKCU\Software\Classes\ms-settings and its subkeys from the registry.

In batch, it would be as simple as: REG DELETE "HKCU\Software\Classes\ms-settings" /F

In python, I tried using winreg:

import winreg
HKCU = winreg.HKEY_CURRENT_USER
REG_PATH = r'Software\Classes\ms-settings'
winreg.DeleteKey(HKCU, REG_PATH)

but it returns WinError 5

PermissionError: [WinError 5] access is denied

Edit: After I've done some research, I realized that in this case, access is denied has nothing to do with admin rights, but its subkeys aren't deleted, so it returns an error. I tried using loops instead:

#Delete registry keys using recursion
import winreg
HKCU = winreg.HKEY_CURRENT_USER
REG_PATH = r'Software\Classes\ms-settings\shell\open\command'

#Delete registry keys
hKey = winreg.CreateKey(HKCU, REG_PATH)
winreg.DeleteValue(hKey, 'DelegateExecute')

#Delete registry paths
key = REG_PATH.split('\\')
for x in range(6,2,-1):
    path = '\\'.join(key[:x])
    winreg.DeleteKey(HKCU, path)

It works, but it's not a practical method. How can you know the name of all subkeys in a key? Is there no built-in function for this in python? Or am I just reinventing the wheel?

ScriptKidd
  • 803
  • 1
  • 5
  • 19
  • 1
    Access denied means access denied - the problem isn't the code per se but your access level, or the user account the script is running as. – Grismar Feb 14 '20 at 00:42
  • That is just one of the many reasons. Even if I run the script as admin, it fails. The real reason is that the subkeys aren't cleared, so the key cannot be deleted. – ScriptKidd Feb 14 '20 at 00:46
  • It helps, buts do I really have to read all of the subkeys and delete each? – ScriptKidd Feb 14 '20 at 00:59
  • As far as I know, there's no such function in the library - which seems a pretty safe design decision. If you do want to do that, I would suggest calling a shell command with this https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/reg-delete – Grismar Feb 14 '20 at 01:09
  • @Grismar anyways, thanks a lot. – ScriptKidd Feb 18 '20 at 00:38

0 Answers0