我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用_winreg.EnumKey()。
def test_non_latin_extension(self): import _winreg class MockWinreg(object): def __getattr__(self, name): if name == 'EnumKey': return lambda key, i: _winreg.EnumKey(key, i) + "\xa3" elif name == 'OpenKey': return lambda key, name: _winreg.OpenKey(key, name.rstrip("\xa3")) elif name == 'QueryValueEx': return lambda subkey, label: (u'?????/???????' , _winreg.REG_SZ) return getattr(_winreg, name) mimetypes._winreg = MockWinreg() try: # this used to throw an exception if registry contained non-Latin # characters in extensions (issue #9291) mimetypes.init() finally: mimetypes._winreg = _winreg
def printNets(username, password): keypath = r"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Unmanaged" key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keypath) print ('[*] Networks you have joined.') for i in range(1): try: guid = _winreg.EnumKey(key, i) netKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keypath+r"\\"+str(guid)) (n, addr, t) = _winreg.EnumValue(netKey, 0) (n, name, t) = _winreg.EnumValue(netKey, 1) macAddr = val2addr(addr) print (' [+] ' + name + ' ' + macAddr) #wiglePrint(username, password, macAddr) _winreg.CloseKey(netKey) except Exception, e: print e break
def enum_keys(reg): if reg: keys = [] try: i = 0 while 1: name = _winreg.EnumKey(reg, i) keys.append(name) i += 1 except WindowsError as e: return keys else: return False
def __del_keys(self): 'Private class method.' try: while True: _winreg.DeleteKey(self.__self, _winreg.EnumKey(self.__self, 0)) except EnvironmentError: pass
def __iter__(self): 'Iterate over the key names.' keys, index = [], 0 try: while True: keys.append(_winreg.EnumKey(self.__self, index)) index += 1 except EnvironmentError: for key in keys: yield key
def __contains__(self, item): 'Check for a key\'s existence.' item, index = item.lower(), 0 try: while True: if _winreg.EnumKey(self.__self, index).lower() == item: return True index += 1 except EnvironmentError: return False
def keys(self): # returns a dict of subkeys if not self._keys: self._keys={} for i in xrange(reg.QueryInfoKey(self.wrk)[0]): name=reg.EnumKey(self.wrk, i).lower() try: self._keys[name]=Key(self, name) except WindowsError: pass return self._keys
def __del_keys(self): 'Private class method.' try: while True: _winreg.DeleteKey(self.__key, _winreg.EnumKey(self.__key, 0)) except EnvironmentError: pass
def __contains__(self, item): 'Check for a key\'s existence.' item = item.lower() for index in xrange(_winreg.QueryInfoKey(self.__key)[0]): if _winreg.EnumKey(self.__key, index).lower() == item: return True return False ################################################################################
def __iter__(self): 'Iterate over the key names.' return iter(tuple(_winreg.EnumKey(self.__key, index) for index in xrange(_winreg.QueryInfoKey(self.__key)[0])))
def enumkey(self, index): """ Enumerate the subkeys of the currently open key """ if not self._hkey: raise RegistryError,"Error: null key" try: return wreg.EnumKey(self._hkey, index) except EnvironmentError, e: raise RegistryError, e
def subkeys(self): """The subkeys of the registry key :type: [:class:`PyHKey`] - A list of keys""" res = [] with ExpectWindowsError(259): for i in itertools.count(): res.append(_winreg.EnumKey(self.phkey, i)) return [PyHKey(self, n) for n in res]
def _enumerate_reg_keys(key): return _RegKeyDict._enumerate_reg(key, _winreg.EnumKey)
def read_subkeys(self, regKey): self._log("Reading subkeys for registry key: %s" % regKey) registryHandles = [] subkeys = [] path = regKey.split("/") hiveName = path.pop(0) hive = reg.ConnectRegistry(None, self.regKeys[hiveName][0]) registryHandle = reg.OpenKey(hive, self.regKeys[hiveName][1]) registryHandles.append(hive) self._log("Connected to registry at location: %s" % hiveName) for step in path: registryHandles.append(registryHandle) registryHandle = reg.OpenKey(registryHandle, step) i = 0 while True: try: subkey = reg.EnumKey(registryHandle, i) self._log("Found subkey: %s" % subkey) subkeys.append(subkey) i += 1 except EnvironmentError: break self._log("Found %d subkeys." % len(subkeys)) self._log("Closing %d registry handles..." % len(registryHandles)) for handle in registryHandles: reg.CloseKey(handle) self._log("Done. Subkey enumeration completed.") return subkeys
def __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! import _winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)"\ "\s+stepping\s+(?P<STP>\d+)",re.IGNORECASE) chnd=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 while 1: try: proc=_winreg.EnumKey(chnd,pnum) except _winreg.error: break else: pnum+=1 info.append({"Processor":proc}) phnd=_winreg.OpenKey(chnd,proc) pidx=0 while True: try: name,value,vtpe=_winreg.EnumValue(phnd,pidx) except _winreg.error: break else: pidx=pidx+1 info[-1][name]=value if name=="Identifier": srch=prgx.search(value) if srch: info[-1]["Family"]=int(srch.group("FML")) info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except: print sys.exc_value,'(ignoring)' self.__class__.info = info
def list(): """Return a list of all time zones known to the system.""" handle = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) tzkey = _winreg.OpenKey(handle, TZKEYNAME) result = [_winreg.EnumKey(tzkey, i) for i in range(_winreg.QueryInfoKey(tzkey)[0])] tzkey.Close() handle.Close() return result
def _reg_query_sub_keys(handle, key, keylist = []): reghandle = reg.OpenKey(handle, key, 0, reg.KEY_READ) try: i = 0 while True: subkey = reg.EnumKey(reghandle, i) i += 1 _reg_query_sub_keys(handle, key + subkey + "\\", keylist) except WindowsError as ex: if ex.winerror == 259: keylist.append(key) finally: reg.CloseKey(reghandle)
def get_installed_pythons(): try: python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore") except WindowsError: # No registered Python installations return {} i = 0 versions = [] while True: try: versions.append(winreg.EnumKey(python_core, i)) i = i + 1 except WindowsError: break exes = dict() for ver in versions: try: path = winreg.QueryValue(python_core, "%s\\InstallPath" % ver) except WindowsError: continue exes[ver] = join(path, "python.exe") winreg.CloseKey(python_core) # Add the major versions # Sort the keys, then repeatedly update the major version entry # Last executable (i.e., highest version) wins with this approach for ver in sorted(exes): exes[ver[0]] = exes[ver] return exes
def __get_key_values(root_key, key): """This method gets the values and subkeys from the given key under the root key. Args: root_key (str): The root key as abbreviated string. Valid values: [hklm, hkcr, hkcu, hku, hkpd, hkcc]. key (str): The subkey starting from the root key. e.g.: SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\interfaces Returns: list. It returns the retrieved values and subkeys or an empty list if data could not be retrieved. """ values = [] i = 0 try: hkey = _winreg.OpenKey(root_key, key, 0, _winreg.KEY_READ) except WindowsError as e: logging.error('Key ({0}) could not be opened: {1}'.format(key, e)) return values while True: try: value = _winreg.EnumKey(hkey, i) values.append(value) i += 1 except WindowsError: logging.info('No more values. Total values: {0}'.format(i)) if hkey: _winreg.CloseKey(hkey) break # no more values return values
def __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! import _winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)" \ "\s+stepping\s+(?P<STP>\d+)", re.IGNORECASE) chnd = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum = 0 while 1: try: proc = _winreg.EnumKey(chnd, pnum) except _winreg.error: break else: pnum += 1 info.append({"Processor": proc}) phnd = _winreg.OpenKey(chnd, proc) pidx = 0 while True: try: name, value, vtpe = _winreg.EnumValue(phnd, pidx) except _winreg.error: break else: pidx = pidx + 1 info[-1][name] = value if name == "Identifier": srch = prgx.search(value) if srch: info[-1]["Family"] = int(srch.group("FML")) info[-1]["Model"] = int(srch.group("MDL")) info[-1]["Stepping"] = int(srch.group("STP")) except: print( str(sys.exc_info()) + '(ignoring)' ) self.__class__.info = info
def list_timezones(): """Return a list of all time zones known to the system.""" l=[] for i in xrange(parentsize): l.append(_winreg.EnumKey(tzparent, i)) return l
def readKeys(keyPath): # return list of Keys explorer = OpenKey(HKEY_LOCAL_MACHINE, keyPath, 0, KEY_READ | KEY_WOW64_64KEY) KeysList = [] for i in xrange(QueryInfoKey(explorer)[0]): name = EnumKey(explorer, i) KeysList.append(name) return KeysList
def get_acroversion(): " Return version of Adobe Acrobat executable or None" import _winreg adobesoft = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'Software\Adobe') for index in range(_winreg.QueryInfoKey(adobesoft)[0]): key = _winreg.EnumKey(adobesoft, index) if "acrobat" in key.lower(): acrokey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'Software\\Adobe\\%s' % key) for index in range(_winreg.QueryInfoKey(acrokey)[0]): numver = _winreg.EnumKey(acrokey, index) try: res = _winreg.QueryValue(_winreg.HKEY_LOCAL_MACHINE, 'Software\\Adobe\\%s\\%s\\InstallPath' % (key, numver)) return res except Exception: pass return None
def next(self): try: k = _winreg.EnumKey(self.key.hkey,self.index) except WindowsError: raise StopIteration else: self.index += 1 return Key(k,self.key)
def iteritems_children(self, access=_winreg.KEY_ALL_ACCESS): i = 0 try: while 1: s = _winreg.EnumKey(self.keyhandle, i) yield s, RegistryDict(self.keyhandle, [s], access) i += 1 except: pass
def enum_all_subkey() : root_key=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,'') key_index=0 return_key_list=[] try : while True : key_name=_winreg.EnumKey(root_key,key_index) key_index+=1 return_key_list.append(key_name) except : pass return return_key_list
def is_pseudo_protocal_key(input_key_name) : key=None try : key=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,input_key_name) except : # Cannot Open This Key .. return False key_index=0 value_index=0 exist_value=False exist_key=False try : while True : value_name,value_value,value_type=_winreg.EnumValue(key,value_index) value_index+=1 if 'URL Protocol'==value_name : exist_value=True except : pass try : while True : key_name=_winreg.EnumKey(key,key_index) key_index+=1 if 'shell'==key_name : try : pseudo_protocal_command=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,input_key_name+'\\shell\\open\\command') exist_key=True except : pass except : pass if exist_value and exist_key : return True return False
def scan_installed_apps(): """ scan installed apps in windows system :return: """ apps_list = [] for key_root in [_winreg.HKEY_CURRENT_USER, _winreg.HKEY_LOCAL_MACHINE]: for key_path in ["SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"]: try: key = _winreg.OpenKey(key_root, key_path) # list all installed Apps i = 0 while True: app = {} sub_key_name = _winreg.EnumKey(key, i) sub_key = _winreg.OpenKey(key, sub_key_name) try: app["display_name"] = _winreg.QueryValueEx(sub_key, "DisplayName")[0] app["path"] = _winreg.QueryValueEx(sub_key, "InstallLocation")[0] apps_list.append(app) except WindowsError: pass i += 1 except WindowsError: pass return apps_list
def list_timezones(): """Return a list of all time zones known to the system.""" l = [] for i in xrange(parentsize): l.append(_winreg.EnumKey(tzparent, i)) return l
def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break try: ctype = ctype.encode(default_encoding) # omit in 3.x! except UnicodeEncodeError: pass else: yield ctype i += 1 default_encoding = sys.getdefaultencoding() with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, r'MIME\Database\Content Type') as mimedb: for ctype in enum_types(mimedb): try: with _winreg.OpenKey(mimedb, ctype) as key: suffix, datatype = _winreg.QueryValueEx(key, 'Extension') except EnvironmentError: continue if datatype != _winreg.REG_SZ: continue try: suffix = suffix.encode(default_encoding) # omit in 3.x! except UnicodeEncodeError: continue self.add_type(ctype, suffix, strict)
def get_localzone_name(): # Windows is special. It has unique time zone names (in several # meanings of the word) available, but unfortunately, they can be # translated to the language of the operating system, so we need to # do a backwards lookup, by going through all time zones and see which # one matches. handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) TZLOCALKEYNAME = r'SYSTEM\CurrentControlSet\Control\TimeZoneInformation' localtz = winreg.OpenKey(handle, TZLOCALKEYNAME) keyvalues = valuestodict(localtz) localtz.Close() if 'TimeZoneKeyName' in keyvalues: # Windows 7 (and Vista?) # For some reason this returns a string with loads of NUL bytes at # least on some systems. I don't know if this is a bug somewhere, I # just work around it. tzkeyname = keyvalues['TimeZoneKeyName'].split('\x00', 1)[0] else: # Windows 2000 or XP # This is the localized name: tzwin = keyvalues['StandardName'] # Open the list of timezones to look up the real name: TZKEYNAME = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones' tzkey = winreg.OpenKey(handle, TZKEYNAME) # Now, match this value to Time Zone information tzkeyname = None for i in range(winreg.QueryInfoKey(tzkey)[0]): subkey = winreg.EnumKey(tzkey, i) sub = winreg.OpenKey(tzkey, subkey) data = valuestodict(sub) sub.Close() if data['Std'] == tzwin: tzkeyname = subkey break tzkey.Close() handle.Close() if tzkeyname is None: raise LookupError('Can not find Windows timezone configuration') timezone = tz_names.get(tzkeyname) if timezone is None: # Nope, that didn't work. Try adding 'Standard Time', # it seems to work a lot of times: timezone = tz_names.get(tzkeyname + ' Standard Time') # Return what we have. if timezone is None: raise pytz.UnknownTimeZoneError('Can not find timezone ' + tzkeyname) return timezone
def read_registry(self): """Extract resolver configuration from the Windows registry.""" lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) want_scan = False try: try: # XP, 2000 tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters') want_scan = True except EnvironmentError: # ME tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\VxD\MSTCP') try: self._config_win32_fromkey(tcp_params) finally: tcp_params.Close() if want_scan: interfaces = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters' r'\Interfaces') try: i = 0 while True: try: guid = _winreg.EnumKey(interfaces, i) i += 1 key = _winreg.OpenKey(interfaces, guid) if not self._win32_is_nic_enabled(lm, guid, key): continue try: self._config_win32_fromkey(key) finally: key.Close() except EnvironmentError: break finally: interfaces.Close() finally: lm.Close()
def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: yield _winreg.EnumKey(mimedb, i) except EnvironmentError: break i += 1 default_encoding = sys.getdefaultencoding() with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr: for subkeyname in enum_types(hkcr): try: with _winreg.OpenKey(hkcr, subkeyname) as subkey: # Only check file extensions if not subkeyname.startswith("."): continue # raises EnvironmentError if no 'Content Type' value mimetype, datatype = _winreg.QueryValueEx( subkey, 'Content Type') if datatype != _winreg.REG_SZ: continue try: mimetype = mimetype.encode(default_encoding) except UnicodeEncodeError: continue self.add_type(mimetype, subkeyname, strict) except EnvironmentError: continue
def __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! if sys.version_info[0] >= 3: import winreg else: import _winreg as winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)"\ "\s+stepping\s+(?P<STP>\d+)", re.IGNORECASE) chnd=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 while True: try: proc=winreg.EnumKey(chnd, pnum) except winreg.error: break else: pnum+=1 info.append({"Processor":proc}) phnd=winreg.OpenKey(chnd, proc) pidx=0 while True: try: name, value, vtpe=winreg.EnumValue(phnd, pidx) except winreg.error: break else: pidx=pidx+1 info[-1][name]=value if name=="Identifier": srch=prgx.search(value) if srch: info[-1]["Family"]=int(srch.group("FML")) info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except: print(sys.exc_info()[1], '(ignoring)') self.__class__.info = info
def read_windows_registry(self, strict=True): """ Load the MIME types database from Windows registry. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ # Windows only if not _winreg: return def enum_types(mimedb): i = 0 while True: try: ctype = _winreg.EnumKey(mimedb, i) except EnvironmentError: break else: if '\0' not in ctype: yield ctype i += 1 default_encoding = sys.getdefaultencoding() with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr: for subkeyname in enum_types(hkcr): try: with _winreg.OpenKey(hkcr, subkeyname) as subkey: # Only check file extensions if not subkeyname.startswith("."): continue # raises EnvironmentError if no 'Content Type' value mimetype, datatype = _winreg.QueryValueEx( subkey, 'Content Type') if datatype != _winreg.REG_SZ: continue try: mimetype = mimetype.encode(default_encoding) except UnicodeEncodeError: continue self.add_type(mimetype, subkeyname, strict) except EnvironmentError: continue
def get_local_data(): tmp_list = [] out_list = [] global g_verbose try: import _winreg as reg except ImportError: print "[-] \'winreg.py\' not found... Is this a Windows system?" sys.exit(1) hReg = reg.ConnectRegistry(None, reg.HKEY_LOCAL_MACHINE) hSystem = reg.OpenKey(hReg, r'SYSTEM') for i in xrange(1024): try: control_name = reg.EnumKey(hSystem, i) if 'controlset' in control_name.lower(): hSessionMan = reg.OpenKey(hReg, 'SYSTEM\\%s\\Control\\Session Manager' % control_name) for i in xrange(1024): try: subkey_name = reg.EnumKey(hSessionMan, i) if ('appcompatibility' in subkey_name.lower() or 'appcompatcache' in subkey_name.lower()): appcompat_key = reg.OpenKey(hSessionMan, subkey_name) bin_data = reg.QueryValueEx(appcompat_key, 'AppCompatCache')[0] tmp_list = read_cache(bin_data) if tmp_list: path_name = 'SYSTEM\\%s\\Control\\Session Manager\\%s' % (control_name, subkey_name) for row in tmp_list: if g_verbose: row.append(path_name) if row not in out_list: out_list.append(row) except EnvironmentError: break except EnvironmentError: break if len(out_list) == 0: return None else: #Add the header and return the list. if g_verbose: out_list.insert(0, output_header + ['Key Path']) return out_list else: #Only return unique entries. out_list = unique_list(out_list) out_list.insert(0, output_header) return out_list # Read a MIR XML zip archive.