我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32api.RegEnumKey()。
def read_keys(base, key): """Return list of registry keys.""" try: handle = RegOpenKeyEx(base, key) except RegError: return None L = [] i = 0 while 1: try: k = RegEnumKey(handle, i) except RegError: break L.append(k) i = i + 1 return L
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 EnumKeys(root): index = 0 ret = [] while 1: try: item = win32api.RegEnumKey(root, index) except win32api.error: break try: # Note this doesn't handle REG_EXPAND_SZ, but the implementation # here doesn't need to - that is handled as the data is read. val = win32api.RegQueryValue(root, item) except win32api.error: val = "" # code using this assumes a string. ret.append((item, val)) index = index + 1 return ret
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 read_keys(base, key): """Return list of registry keys.""" try: handle = RegOpenKeyEx(base, key) except RegError: return None L = [] i = 0 while True: try: k = RegEnumKey(handle, i) except RegError: break L.append(k) i += 1 return L
def load_macros(self, version): vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir") self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir") net = r"Software\Microsoft\.NETFramework" self.set_macro("FrameworkDir", net, "installroot") try: if version > 7.0: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") except KeyError: raise DistutilsPlatformError, \ ("""Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""") p = r"Software\Microsoft\NET Framework Setup\Product" for base in HKEYS: try: h = RegOpenKeyEx(base, p) except RegError: continue key = RegEnumKey(h, 0) d = read_values(base, r"%s\%s" % (p, key)) self.macros["$(FrameworkVersion)"] = d["version"]
def getSoftwareList(self): try: hCounter=0 hAttCounter=0 # connecting to the base hHandle = win32api.RegConnectRegistry(None,win32con.HKEY_LOCAL_MACHINE) # getting the machine name and domain name hCompName = win32api.GetComputerName() hDomainName = win32api.GetDomainName() # opening the sub key to get the list of Softwares installed hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,self.CONST_SW_SUBKEY,0,win32con.KEY_ALL_ACCESS) # get the total no. of sub keys hNoOfSubNodes = win32api.RegQueryInfoKey(hHandle) # delete the entire data and insert it again #deleteMachineSW(hCompName,hDomainName) # browsing each sub Key which can be Applications installed while hCounter < hNoOfSubNodes[0]: hAppName = win32api.RegEnumKey(hHandle,hCounter) hPath = self.CONST_SW_SUBKEY + "\\" + hAppName # initialising hAttCounter hAttCounter = 0 hOpenApp = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,hPath,0,win32con.KEY_ALL_ACCESS) # [1] will give the no. of attributes in this sub key hKeyCount = win32api.RegQueryInfoKey(hOpenApp) hMaxKeyCount = hKeyCount[1] hSWName = "" hSWVersion = "" while hAttCounter < hMaxKeyCount: hData = win32api.RegEnumValue(hOpenApp,hAttCounter) if hData[0]== "DisplayName": hSWName = hData[1] self.preparefile("SW Name",hSWName) elif hData[0]== "DisplayVersion": hSWVersion = hData[1] self.preparefile("SW Version",hSWVersion) hAttCounter = hAttCounter + 1 #if (hSWName !=""): #insertMachineSW(hCompName,hDomainName,hSWName,hSWVersion) hCounter = hCounter + 1 except: self.preparefile("Exception","In exception in getSoftwareList")
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 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 _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 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
def CheckPythonPaths(verbose): if verbose: print("Python Paths:") # Check the core path if verbose: print("\tCore Path:", end=' ') try: appPath = win32api.RegQueryValue(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath") except win32api.error as 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+":", end=' ') 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 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 as xxx_todo_changeme2: (code, fn, msg) = xxx_todo_changeme2.args 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 as xxx_todo_changeme: (code, fn, msg) = xxx_todo_changeme.args 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 load_macros(self, version): vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir") self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir") net = r"Software\Microsoft\.NETFramework" self.set_macro("FrameworkDir", net, "installroot") try: if version > 7.0: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") except KeyError as exc: # raise DistutilsPlatformError( """Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""") p = r"Software\Microsoft\NET Framework Setup\Product" for base in HKEYS: try: h = RegOpenKeyEx(base, p) except RegError: continue key = RegEnumKey(h, 0) d = read_values(base, r"%s\%s" % (p, key)) self.macros["$(FrameworkVersion)"] = d["version"]