Python _winreg 模块,EnumKey() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用_winreg.EnumKey()

项目:oil    作者:oilshell    | 项目源码 | 文件源码
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
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
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
项目:WintersWrath    作者:Elfsong    | 项目源码 | 文件源码
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
项目:Stitch    作者:nathanlopez    | 项目源码 | 文件源码
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
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __del_keys(self):
        'Private class method.'
        try:
            while True:
                _winreg.DeleteKey(self.__self, _winreg.EnumKey(self.__self, 0))
        except EnvironmentError:
            pass
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __del_keys(self):
        'Private class method.'
        try:
            while True:
                _winreg.DeleteKey(self.__key, _winreg.EnumKey(self.__key, 0))
        except EnvironmentError:
            pass
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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

################################################################################
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __del_keys(self):
        'Private class method.'
        try:
            while True:
                _winreg.DeleteKey(self.__key, _winreg.EnumKey(self.__key, 0))
        except EnvironmentError:
            pass
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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])))
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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

################################################################################
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
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]
项目:purelove    作者:hucmosin    | 项目源码 | 文件源码
def _enumerate_reg_keys(key):
        return _RegKeyDict._enumerate_reg(key, _winreg.EnumKey)
项目:csm    作者:gnzsystems    | 项目源码 | 文件源码
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
项目:aerospike-telemetry-agent    作者:aerospike    | 项目源码 | 文件源码
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
项目:Crunchyroll-XML-Decoder    作者:jaw20    | 项目源码 | 文件源码
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
项目:constructor    作者:conda    | 项目源码 | 文件源码
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)
项目:NeuroMobile    作者:AndrewADykman    | 项目源码 | 文件源码
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
项目:NeuroMobile    作者:AndrewADykman    | 项目源码 | 文件源码
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
项目:django-lti-provider    作者:ccnmtl    | 项目源码 | 文件源码
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
项目:remoteControlPPT    作者:htwenning    | 项目源码 | 文件源码
def _enumerate_reg_keys(key):
        return _RegKeyDict._enumerate_reg(key, _winreg.EnumKey)
项目:r2com    作者:newlog    | 项目源码 | 文件源码
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
项目:zorro    作者:C-CINA    | 项目源码 | 文件源码
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
项目:python-card-me    作者:tBaxter    | 项目源码 | 文件源码
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
项目:Panorama    作者:AlmCo    | 项目源码 | 文件源码
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
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
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
项目:keypirinha-plugins    作者:EhsanKia    | 项目源码 | 文件源码
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)
项目:maestro    作者:InWorldz    | 项目源码 | 文件源码
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
项目:pseudo-protocals-digger    作者:lcatro    | 项目源码 | 文件源码
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
项目:pseudo-protocals-digger    作者:lcatro    | 项目源码 | 文件源码
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
项目:CNCGToolKit    作者:cineuse    | 项目源码 | 文件源码
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
项目:tracecode-toolkit    作者:nexB    | 项目源码 | 文件源码
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
项目:vobject    作者:eventable    | 项目源码 | 文件源码
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
项目:vobject    作者:eventable    | 项目源码 | 文件源码
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
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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()
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
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()
项目:radar    作者:amoose136    | 项目源码 | 文件源码
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
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
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()
项目:SameKeyProxy    作者:xzhou    | 项目源码 | 文件源码
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()
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
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
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
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
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
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()
项目:appcompatprocessor    作者:mbevilacqua    | 项目源码 | 文件源码
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.