def _GetServiceShortName(longName):
# looks up a services name
# from the display name
# Thanks to Andy McKay for this code.
access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access)
num = win32api.RegQueryInfoKey(hkey)[0]
longName = longName.lower()
# loop through number of subkeys
for x in range(0, num):
# find service name, open subkey
svc = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, svc, 0, access)
try:
# find display name
thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
if thisName.lower() == longName:
return svc
except win32api.error:
# in case there is no key called DisplayName
pass
return None
# Open a service given either it's long or short name.
python类RegOpenKey()的实例源码
def __FindSvcDeps(findName):
if type(findName) is pywintypes.UnicodeType: findName = str(findName)
dict = {}
k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services")
num = 0
while 1:
try:
svc = win32api.RegEnumKey(k, num)
except win32api.error:
break
num = num + 1
sk = win32api.RegOpenKey(k, svc)
try:
deps, typ = win32api.RegQueryValueEx(sk, "DependOnService")
except win32api.error:
deps = ()
for dep in deps:
dep = dep.lower()
dep_on = dict.get(dep, [])
dep_on.append(svc)
dict[dep]=dep_on
return __ResolveDeps(findName, dict)
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 FindHelpPath(helpFile, helpDesc, searchPaths):
# See if the current registry entry is OK
import os, win32api, win32con
try:
key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS)
try:
try:
path = win32api.RegQueryValueEx(key, helpDesc)[0]
if FileExists(os.path.join(path, helpFile)):
return os.path.abspath(path)
except win32api.error:
pass # no registry entry.
finally:
key.Close()
except win32api.error:
pass
for pathLook in searchPaths:
if FileExists(os.path.join(pathLook, helpFile)):
return os.path.abspath(pathLook)
pathLook = os.path.join(pathLook, "Help")
if FileExists(os.path.join( pathLook, helpFile)):
return os.path.abspath(pathLook)
raise error("The help file %s can not be located" % helpFile)
def WriteToolMenuItems( items ):
# Items is a list of (menu, command)
# Delete the entire registry tree.
try:
mainKey = win32ui.GetAppRegistryKey()
toolKey = win32api.RegOpenKey(mainKey, "Tools Menu")
except win32ui.error:
toolKey = None
if toolKey is not None:
while 1:
try:
subkey = win32api.RegEnumKey(toolKey, 0)
except win32api.error:
break
win32api.RegDeleteKey(toolKey, subkey)
# Keys are now removed - write the new ones.
# But first check if we have the defaults - and if so, dont write anything!
if items==defaultToolMenuItems:
return
itemNo = 1
for menu, cmd in items:
win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "", menu)
win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "Command", cmd)
itemNo = itemNo + 1
def GetSubList(self):
keyStr = regutil.BuildDefaultPythonKey() + "\\PythonPath"
hKey = win32api.RegOpenKey(regutil.GetRootKey(), keyStr)
try:
ret = []
ret.append(HLIProjectRoot("", "Standard Python Library")) # The core path.
index = 0
while 1:
try:
ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index)))
index = index + 1
except win32api.error:
break
return ret
finally:
win32api.RegCloseKey(hKey)
def GetSubList(self):
hkey = win32api.RegOpenKey(self.keyRoot, self.keyName)
win32ui.DoWaitCursor(1)
try:
keyNum = 0
ret = []
while 1:
try:
key = win32api.RegEnumKey(hkey, keyNum)
except win32api.error:
break
ret.append(HLIRegistryKey(self.keyRoot, self.keyName + "\\" + key, key))
keyNum = keyNum + 1
finally:
win32api.RegCloseKey(hkey)
win32ui.DoWaitCursor(0)
return ret
def _GetServiceShortName(longName):
# looks up a services name
# from the display name
# Thanks to Andy McKay for this code.
access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access)
num = win32api.RegQueryInfoKey(hkey)[0]
longName = longName.lower()
# loop through number of subkeys
for x in range(0, num):
# find service name, open subkey
svc = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, svc, 0, access)
try:
# find display name
thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
if thisName.lower() == longName:
return svc
except win32api.error:
# in case there is no key called DisplayName
pass
return None
# Open a service given either it's long or short name.
def __FindSvcDeps(findName):
if type(findName) is pywintypes.UnicodeType: findName = str(findName)
dict = {}
k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services")
num = 0
while 1:
try:
svc = win32api.RegEnumKey(k, num)
except win32api.error:
break
num = num + 1
sk = win32api.RegOpenKey(k, svc)
try:
deps, typ = win32api.RegQueryValueEx(sk, "DependOnService")
except win32api.error:
deps = ()
for dep in deps:
dep = dep.lower()
dep_on = dict.get(dep, [])
dep_on.append(svc)
dict[dep]=dep_on
return __ResolveDeps(findName, dict)
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 WriteToolMenuItems( items ):
# Items is a list of (menu, command)
# Delete the entire registry tree.
try:
mainKey = win32ui.GetAppRegistryKey()
toolKey = win32api.RegOpenKey(mainKey, "Tools Menu")
except win32ui.error:
toolKey = None
if toolKey is not None:
while 1:
try:
subkey = win32api.RegEnumKey(toolKey, 0)
except win32api.error:
break
win32api.RegDeleteKey(toolKey, subkey)
# Keys are now removed - write the new ones.
# But first check if we have the defaults - and if so, dont write anything!
if items==defaultToolMenuItems:
return
itemNo = 1
for menu, cmd in items:
win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "", menu)
win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "Command", cmd)
itemNo = itemNo + 1
def GetSubList(self):
keyStr = regutil.BuildDefaultPythonKey() + "\\PythonPath"
hKey = win32api.RegOpenKey(regutil.GetRootKey(), keyStr)
try:
ret = []
ret.append(HLIProjectRoot("", "Standard Python Library")) # The core path.
index = 0
while 1:
try:
ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index)))
index = index + 1
except win32api.error:
break
return ret
finally:
win32api.RegCloseKey(hKey)
def UpdateForRegItem(self, item):
self.DeleteAllItems()
hkey = win32api.RegOpenKey(item.keyRoot, item.keyName)
try:
valNum = 0
ret = []
while 1:
try:
res = win32api.RegEnumValue(hkey, valNum)
except win32api.error:
break
name = res[0]
if not name: name = "(Default)"
self.InsertItem(valNum, name)
self.SetItemText(valNum, 1, str(res[1]))
valNum = valNum + 1
finally:
win32api.RegCloseKey(hkey)
def GetSubList(self):
hkey = win32api.RegOpenKey(self.keyRoot, self.keyName)
win32ui.DoWaitCursor(1)
try:
keyNum = 0
ret = []
while 1:
try:
key = win32api.RegEnumKey(hkey, keyNum)
except win32api.error:
break
ret.append(HLIRegistryKey(self.keyRoot, self.keyName + "\\" + key, key))
keyNum = keyNum + 1
finally:
win32api.RegCloseKey(hkey)
win32ui.DoWaitCursor(0)
return ret
def FindHelpPath(helpFile, helpDesc, searchPaths):
# See if the current registry entry is OK
import os, win32api, win32con
try:
key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS)
try:
try:
path = win32api.RegQueryValueEx(key, helpDesc)[0]
if FileExists(os.path.join(path, helpFile)):
return os.path.abspath(path)
except win32api.error:
pass # no registry entry.
finally:
key.Close()
except win32api.error:
pass
for pathLook in searchPaths:
if FileExists(os.path.join(pathLook, helpFile)):
return os.path.abspath(pathLook)
pathLook = os.path.join(pathLook, "Help")
if FileExists(os.path.join( pathLook, helpFile)):
return os.path.abspath(pathLook)
raise error("The help file %s can not be located" % helpFile)
def _GetServiceShortName(longName):
# looks up a services name
# from the display name
# Thanks to Andy McKay for this code.
access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access)
num = win32api.RegQueryInfoKey(hkey)[0]
longName = longName.lower()
# loop through number of subkeys
for x in range(0, num):
# find service name, open subkey
svc = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, svc, 0, access)
try:
# find display name
thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
if thisName.lower() == longName:
return svc
except win32api.error:
# in case there is no key called DisplayName
pass
return None
# Open a service given either it's long or short name.
def __FindSvcDeps(findName):
if type(findName) is pywintypes.UnicodeType: findName = str(findName)
dict = {}
k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services")
num = 0
while 1:
try:
svc = win32api.RegEnumKey(k, num)
except win32api.error:
break
num = num + 1
sk = win32api.RegOpenKey(k, svc)
try:
deps, typ = win32api.RegQueryValueEx(sk, "DependOnService")
except win32api.error:
deps = ()
for dep in deps:
dep = dep.lower()
dep_on = dict.get(dep, [])
dep_on.append(svc)
dict[dep]=dep_on
return __ResolveDeps(findName, dict)
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 FormatMessage( eventLogRecord, logType="Application" ):
"""Given a tuple from ReadEventLog, and optionally where the event
record came from, load the message, and process message inserts.
Note that this function may raise win32api.error. See also the
function SafeFormatMessage which will return None if the message can
not be processed.
"""
# From the event log source name, we know the name of the registry
# key to look under for the name of the message DLL that contains
# the messages we need to extract with FormatMessage. So first get
# the event log source name...
keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName)
# Now open this key and get the EventMessageFile value, which is
# the name of the message DLL.
handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName)
try:
dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";")
# Win2k etc appear to allow multiple DLL names
data = None
for dllName in dllNames:
try:
# Expand environment variable strings in the message DLL path name,
# in case any are there.
dllName = win32api.ExpandEnvironmentStrings(dllName)
dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE)
try:
data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE,
dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts)
finally:
win32api.FreeLibrary(dllHandle)
except win32api.error:
pass # Not in this DLL - try the next
if data is not None:
break
finally:
win32api.RegCloseKey(handle)
return data or u'' # Don't want "None" ever being returned.
def CheckPythonPaths(verbose):
if verbose: print "Python Paths:"
# Check the core path
if verbose: print "\tCore Path:",
try:
appPath = win32api.RegQueryValue(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath")
except win32api.error, exc:
print "** does not exist - ", exc.strerror
problem = CheckPathString(appPath)
if problem:
print problem
else:
if verbose: print appPath
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ)
try:
keyNo = 0
while 1:
try:
appName = win32api.RegEnumKey(key, keyNo)
appPath = win32api.RegQueryValue(key, appName)
if verbose: print "\t"+appName+":",
if appPath:
problem = CheckPathString(appPath)
if problem:
print problem
else:
if verbose: print appPath
else:
if verbose: print "(empty)"
keyNo = keyNo + 1
except win32api.error:
break
finally:
win32api.RegCloseKey(key)
def CheckHelpFiles(verbose):
if verbose: print "Help Files:"
try:
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ)
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
return
try:
keyNo = 0
while 1:
try:
helpDesc = win32api.RegEnumKey(key, keyNo)
helpFile = win32api.RegQueryValue(key, helpDesc)
if verbose: print "\t"+helpDesc+":",
# query the os section.
try:
os.stat(helpFile )
if verbose: print helpFile
except os.error:
print "** Help file %s does not exist" % helpFile
keyNo = keyNo + 1
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS:
raise
break
finally:
win32api.RegCloseKey(key)
def CheckRegisteredModules(verbose):
# Check out all registered modules.
k=regutil.BuildDefaultPythonKey() + "\\Modules"
try:
keyhandle = win32api.RegOpenKey(regutil.GetRootKey(), k)
print "WARNING: 'Modules' registry entry is deprectated and evil!"
except win32api.error, exc:
import winerror
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
raise
return
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 LocateSpecificServiceExe(serviceName):
# Given the name of a specific service, return the .EXE name _it_ uses
# (which may or may not be the Python Service EXE
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS)
try:
return win32api.RegQueryValueEx(hkey, "ImagePath")[0]
finally:
hkey.Close()
def recurse_delete_key(path, base=win32con.HKEY_CLASSES_ROOT):
"""Recursively delete registry keys.
This is needed since you can't blast a key when subkeys exist.
"""
try:
h = win32api.RegOpenKey(base, path)
except win32api.error, (code, fn, msg):
if code != winerror.ERROR_FILE_NOT_FOUND:
raise win32api.error(code, fn, msg)
else:
# parent key found and opened successfully. do some work, making sure
# to always close the thing (error or no).
try:
# remove all of the subkeys
while 1:
try:
subkeyname = win32api.RegEnumKey(h, 0)
except win32api.error, (code, fn, msg):
if code != winerror.ERROR_NO_MORE_ITEMS:
raise win32api.error(code, fn, msg)
break
recurse_delete_key(path + '\\' + subkeyname, base)
# remove the parent key
_remove_key(path, base)
finally:
win32api.RegCloseKey(h)
def GetSubList(self):
# Explicit lookup in the registry.
ret = []
key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
win32ui.DoWaitCursor(1)
try:
num = 0
while 1:
try:
keyName = win32api.RegEnumKey(key, num)
except win32api.error:
break
# Enumerate all version info
subKey = win32api.RegOpenKey(key, keyName)
name = None
try:
subNum = 0
bestVersion = 0.0
while 1:
try:
versionStr = win32api.RegEnumKey(subKey, subNum)
except win32api.error:
break
try:
versionFlt = float(versionStr)
except ValueError:
versionFlt = 0 # ????
if versionFlt > bestVersion:
bestVersion = versionFlt
name = win32api.RegQueryValue(subKey, versionStr)
subNum = subNum + 1
finally:
win32api.RegCloseKey(subKey)
if name is not None:
ret.append(HLIRegisteredTypeLibrary((keyName, versionStr), name))
num = num + 1
finally:
win32api.RegCloseKey(key)
win32ui.DoWaitCursor(0)
ret.sort()
return ret
def getRegistryParameters(servicename):
key=win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\"+servicename)
try:
try:
(commandLine, regtype) = win32api.RegQueryValueEx(key,pyroArgsRegkeyName)
return commandLine
except:
pass
finally:
key.Close()
createRegistryParameters(servicename, pyroArgsRegkeyName)
return ""
def _watch_thread(self, hive, watchKey, name, callback):
self._log("Watch thread active for key: %s" % name, messageType="DEBUG")
while self.alive:
watchHandle = win32api.RegOpenKey(hive, watchKey, 0, win32con.KEY_NOTIFY)
win32api.RegNotifyChangeKeyValue(watchHandle, False, win32api.REG_NOTIFY_CHANGE_NAME, None, False)
win32api.RegCloseKey(watchHandle)
self._log("Change detected in thread: %s" % name, messageType="DEBUG")
callback(name)
self._log("Watch thread returning for key: %s" % name, messageType="DEBUG")
return
def recurse_delete_key(path, base=win32con.HKEY_CLASSES_ROOT):
"""Recursively delete registry keys.
This is needed since you can't blast a key when subkeys exist.
"""
try:
h = win32api.RegOpenKey(base, path)
except win32api.error, (code, fn, msg):
if code != winerror.ERROR_FILE_NOT_FOUND:
raise win32api.error(code, fn, msg)
else:
# parent key found and opened successfully. do some work, making sure
# to always close the thing (error or no).
try:
# remove all of the subkeys
while 1:
try:
subkeyname = win32api.RegEnumKey(h, 0)
except win32api.error, (code, fn, msg):
if code != winerror.ERROR_NO_MORE_ITEMS:
raise win32api.error(code, fn, msg)
break
recurse_delete_key(path + '\\' + subkeyname, base)
# remove the parent key
_remove_key(path, base)
finally:
win32api.RegCloseKey(h)
def GetSubList(self):
# Explicit lookup in the registry.
ret = []
key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
win32ui.DoWaitCursor(1)
try:
num = 0
while 1:
try:
keyName = win32api.RegEnumKey(key, num)
except win32api.error:
break
# Enumerate all version info
subKey = win32api.RegOpenKey(key, keyName)
name = None
try:
subNum = 0
bestVersion = 0.0
while 1:
try:
versionStr = win32api.RegEnumKey(subKey, subNum)
except win32api.error:
break
try:
versionFlt = float(versionStr)
except ValueError:
versionFlt = 0 # ????
if versionFlt > bestVersion:
bestVersion = versionFlt
name = win32api.RegQueryValue(subKey, versionStr)
subNum = subNum + 1
finally:
win32api.RegCloseKey(subKey)
if name is not None:
ret.append(HLIRegisteredTypeLibrary((keyName, versionStr), name))
num = num + 1
finally:
win32api.RegCloseKey(key)
win32ui.DoWaitCursor(0)
ret.sort()
return ret