Reputation: 189
I want to save the registry key "Run" using _winreg in Python. This is my code:
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Run')
_winreg.SaveKey(key, "C:\key.reg")
When executing, I get a Windows error message: "A required privilege is not held by the client"
Can anyone see what is wrong?
Upvotes: 1
Views: 2154
Reputation: 2984
Modify your code as below. It works fine if it is Run as Administrator
. I have tested it on Win7 64 bit
import os, sys
import _winreg
import win32api
import win32security
#
# You need to have SeBackupPrivilege enabled for this to work
#
priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
hToken = win32security.OpenProcessToken (win32api.GetCurrentProcess (), priv_flags)
privilege_id = win32security.LookupPrivilegeValue (None, "SeBackupPrivilege")
win32security.AdjustTokenPrivileges (hToken, 0, [(privilege_id, win32security.SE_PRIVILEGE_ENABLED)])
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Run')
filepath = r'C:\key.reg'
if os.path.exists (filepath):
os.unlink (filepath)
_winreg.SaveKey (key, filepath)
Note: if win32api
& win32security
are missing, install them from here
Reference: Here
Upvotes: 4