RegRestoreKey.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import win32api, win32security
  2. import win32con, ntsecuritycon, winnt
  3. import os
  4. temp_dir=win32api.GetTempPath()
  5. fname=win32api.GetTempFileName(temp_dir,'rsk')[0]
  6. print(fname)
  7. ## file can't exist
  8. os.remove(fname)
  9. ## enable backup and restore privs
  10. required_privs = ((win32security.LookupPrivilegeValue('',ntsecuritycon.SE_BACKUP_NAME),win32con.SE_PRIVILEGE_ENABLED),
  11. (win32security.LookupPrivilegeValue('',ntsecuritycon.SE_RESTORE_NAME),win32con.SE_PRIVILEGE_ENABLED)
  12. )
  13. ph = win32api.GetCurrentProcess()
  14. th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ|win32con.TOKEN_ADJUST_PRIVILEGES)
  15. adjusted_privs=win32security.AdjustTokenPrivileges(th,0,required_privs)
  16. try:
  17. sa=win32security.SECURITY_ATTRIBUTES()
  18. my_sid = win32security.GetTokenInformation(th,ntsecuritycon.TokenUser)[0]
  19. sa.SECURITY_DESCRIPTOR.SetSecurityDescriptorOwner(my_sid,0)
  20. k, disp=win32api.RegCreateKeyEx(win32con.HKEY_CURRENT_USER, 'Python test key', SecurityAttributes=sa,
  21. samDesired=win32con.KEY_ALL_ACCESS, Class='some class', Options=0)
  22. win32api.RegSetValue(k, None, win32con.REG_SZ, 'Default value for python test key')
  23. subk, disp=win32api.RegCreateKeyEx(k, 'python test subkey', SecurityAttributes=sa,
  24. samDesired=win32con.KEY_ALL_ACCESS, Class='some other class', Options=0)
  25. win32api.RegSetValue(subk, None, win32con.REG_SZ, 'Default value for subkey')
  26. win32api.RegSaveKeyEx(k, fname, Flags=winnt.REG_STANDARD_FORMAT, SecurityAttributes=sa)
  27. restored_key, disp=win32api.RegCreateKeyEx(win32con.HKEY_CURRENT_USER, 'Python test key(restored)', SecurityAttributes=sa,
  28. samDesired=win32con.KEY_ALL_ACCESS, Class='restored class', Options=0)
  29. win32api.RegRestoreKey(restored_key, fname)
  30. finally:
  31. win32security.AdjustTokenPrivileges(th, 0, adjusted_privs)