我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32api.RegOpenKey()。
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 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 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 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 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 UnregisterHelpFile(helpFile, helpDesc = None): """Unregister a help file in the registry. helpFile -- the base name of the help file. helpDesc -- A description for the help file. If None, the helpFile param is used. """ key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS) try: try: win32api.RegDeleteValue(key, helpFile) except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise finally: win32api.RegCloseKey(key) # Now de-register with Python itself. if helpDesc is None: helpDesc = helpFile try: win32api.RegDeleteKey(GetRootKey(), BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc) except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise
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 _ListAllHelpFilesInRoot(root): """Returns a list of (helpDesc, helpFname) for all registered help files """ import regutil retList = [] try: key = win32api.RegOpenKey(root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ) except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise return retList try: keyNo = 0 while 1: try: helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) retList.append((helpDesc, helpFile)) keyNo = keyNo + 1 except win32api.error, exc: import winerror if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS: raise break finally: win32api.RegCloseKey(key) return retList
def GetItemsCurrentValue(self, item, valueName): hkey = win32api.RegOpenKey(item.keyRoot, item.keyName) try: val, type = win32api.RegQueryValueEx(hkey, valueName) if type != win32con.REG_SZ: raise TypeError("Only strings can be edited") return val finally: win32api.RegCloseKey(hkey)
def SetItemsCurrentValue(self, item, valueName, value): # ** Assumes already checked is a string. hkey = win32api.RegOpenKey(item.keyRoot, item.keyName , 0, win32con.KEY_SET_VALUE) try: win32api.RegSetValueEx(hkey, valueName, 0, win32con.REG_SZ, value) finally: win32api.RegCloseKey(hkey)
def IsExpandable(self): # All keys are expandable, even if they currently have zero children. return 1 ## hkey = win32api.RegOpenKey(self.keyRoot, self.keyName) ## try: ## keys, vals, dt = win32api.RegQueryInfoKey(hkey) ## return (keys>0) ## finally: ## win32api.RegCloseKey(hkey)
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 _ListAllHelpFilesInRoot(root): """Returns a list of (helpDesc, helpFname) for all registered help files """ import regutil retList = [] try: key = win32api.RegOpenKey(root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ) except win32api.error as exc: import winerror if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND: raise return retList try: keyNo = 0 while 1: try: helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) retList.append((helpDesc, helpFile)) keyNo = keyNo + 1 except win32api.error as exc: import winerror if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS: raise break finally: win32api.RegCloseKey(key) return retList