Search code examples
pythonwindowsregistrypsexec

Run reg delete command inside Python script


I want to delete some registry keys in Windows using Python 3 script.

For achieve this I used winreg module inside my script, in general it works fine,
but unfortunately for subkeys under: HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USBSTOR
I got errors: "[WinError 5] Access denied", even if I run my script with Administrator privileges.

For resolve this unpleasant problem I decide call inside script reg delete Windows utility as SYSTEM using PsExec:

# E.g. path is HKLM\SYSTEM\ControlSet001\Enum\USBSTOR\Disk&Ven_bla_bla_bla
path = "delete \"" + path + "\"" + " /f"

psPath = os.getcwd() + "\\PsTools\\PsExec64.exe"

subprocess.call([psPath, "-accepteula", "-s", "C:\\Windows\\System32\\reg.exe", path], stderr=subprocess.PIPE, stdout=subprocess.PIPE)

But code above doesn't work, could you please help me find where the mistake in this code?


Solution

  • I modified code as follow and now all is works well:

    psPath = os.getcwd() + "\\PsTools\\PsExec64.exe"
    subprocess.run([psPath, "-accepteula", "-s", "C:\\Windows\\System32\\reg.exe", "delete", path, "/f"])