Ejemplo n.º 1
0
def get_dnsserver_list():
    import os
    if os.name == 'nt':
        import winreg
        NameServers = []
        INTERFACES_PATH = 'SYSTEM\\CurrentControlSet\\Services\\Tcpip%s\\Parameters\\Interfaces\\'
        for v in ('', '6'):
            interfaces_path = INTERFACES_PATH % v
            interfaces = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, interfaces_path)
            sub_key_num, _, _ = winreg.QueryInfoKey(interfaces)
            for i in range(sub_key_num):
                try:
                    interface_path = interfaces_path + winreg.EnumKey(interfaces, i)
                    interface = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, interface_path)
                    NameServer, _ = winreg.QueryValueEx(interface, 'NameServer')
                    winreg.CloseKey(interface)
                    if NameServer:
                        NameServers += NameServer.split(',')
                except:
                    pass
            winreg.CloseKey(interfaces)
        return NameServers
    elif os.path.isfile('/etc/resolv.conf'):
        with open('/etc/resolv.conf', 'rb') as fp:
            return re.findall(r'(?m)^nameserver\s+(\S+)', fp.read())
    else:
        import sys
        logging.warning('get_dnsserver_list 失败:不支持 "%s-%s" 平台', sys.platform, os.name)
        return []
Ejemplo n.º 2
0
def find_browsers():
	try:
		import winreg as _winreg
	except:
		import _winreg

	windir = os.getenv('windir')
	key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, os.path.join('Software', 'Clients', 'StartMenuInternet'))
	count = _winreg.QueryInfoKey(key)[0]

	browsers = []
	found_msedge = False
	while count > 0:
		subkey = _winreg.EnumKey(key, count - 1)
		try:
			browsers.append({
				'name': _winreg.QueryValue(key, subkey),
				'command': _winreg.QueryValue(key, os.path.join(subkey, 'shell', 'open', 'command'))
			})
			if subkey == 'Microsoft Edge':
				found_msedge = True
		except:
			pass
		count -= 1

	if not found_msedge and \
		os.path.exists(os.path.join(windir, 'SystemApps', 'Microsoft.MicrosoftEdge_8wekyb3d8bbwe', 'MicrosoftEdge.exe')):
		browsers.append({
			'name': 'Microsoft Edge',
			'command': os.path.join(windir, 'explorer.exe') + ' "microsoft-edge:%s "'
		})

	return browsers
Ejemplo n.º 3
0
def wirelessNetworks():
    #Check for all recorded connections to wireless networks and print results to the screen
    #Results will be in the form 'DNS Name: SSID'
    print(
        "Attempting enumeration of HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Unmanaged"
    )
    print("--- DNS Suffix: SSID")
    checkKey = winreg.CreateKey(
        winreg.HKEY_LOCAL_MACHINE,
        'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Unmanaged'
    )
    numValues = winreg.QueryInfoKey(checkKey)[0]
    if numValues > 0:
        for index in range(numValues):
            nameKey = winreg.EnumKey(checkKey, index)
            trueKey = winreg.CreateKey(
                winreg.HKEY_LOCAL_MACHINE,
                'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkList\\Signatures\\Unmanaged\\'
                + nameKey)
            DnsSuffix = winreg.EnumValue(trueKey, 3)
            FirstNetwork = winreg.EnumValue(trueKey, 4)
            print("--- {0}: {1}".format(DnsSuffix[1], FirstNetwork[1]))
        print("No additional Wireless Network Connections Found\n")
    else:
        print("No Values in this Key\n")
Ejemplo n.º 4
0
def _get_win_reg_info(key_path, hive, flag, subkeys):
    """
    See: https://stackoverflow.com/q/53132434
    """
    import winreg

    reg = winreg.ConnectRegistry(None, hive)
    software_list = []
    try:
        key = winreg.OpenKey(reg, key_path, 0, winreg.KEY_READ | flag)
        count_subkey = winreg.QueryInfoKey(key)[0]

        for index in range(count_subkey):
            software = {}
            try:
                subkey_name = winreg.EnumKey(key, index)
                if not (subkey_name.startswith('{')
                        and subkey_name.endswith('}')):
                    software['key'] = subkey_name
                    subkey = winreg.OpenKey(key, subkey_name)
                    for property in subkeys:
                        try:
                            value = winreg.QueryValueEx(subkey, property)[0]
                            software[property] = value
                        except EnvironmentError:
                            software[property] = ''
                    software_list.append(software)
            except EnvironmentError:
                continue
    except Exception:
        pass

    return software_list
Ejemplo n.º 5
0
def win32InstalledFonts(directory=None, fontext='ttf'):
    """
    Search for fonts in the specified font directory, or use the
    system directories if none given.  A list of TrueType font
    filenames are returned by default, or AFM fonts if *fontext* ==
    'afm'.
    """

    import winreg

    if directory is None:
        directory = win32FontDirectory()

    fontext = get_fontext_synonyms(fontext)

    items = set()
    for fontdir in MSFontDirectories:
        try:
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir) as local:
                for j in range(winreg.QueryInfoKey(local)[1]):
                    key, direc, tp = winreg.EnumValue(local, j)
                    if not isinstance(direc, str):
                        continue
                    # Work around for https://bugs.python.org/issue25778, which
                    # is fixed in Py>=3.6.1.
                    direc = direc.split("\0", 1)[0]
                    path = Path(directory, direc).resolve()
                    if path.suffix.lower() in fontext:
                        items.add(str(path))
                return list(items)
        except (OSError, MemoryError):
            continue
    return None
Ejemplo n.º 6
0
def _get_win32_installed_fonts():
    """List the font paths known to the Windows registry."""
    import winreg
    items = set()
    # Search and resolve fonts listed in the registry.
    for domain, base_dirs in [
        (winreg.HKEY_LOCAL_MACHINE, [win32FontDirectory()]),  # System.
        (winreg.HKEY_CURRENT_USER, MSUserFontDirectories),  # User.
    ]:
        for base_dir in base_dirs:
            for reg_path in MSFontDirectories:
                try:
                    with winreg.OpenKey(domain, reg_path) as local:
                        for j in range(winreg.QueryInfoKey(local)[1]):
                            # value may contain the filename of the font or its
                            # absolute path.
                            key, value, tp = winreg.EnumValue(local, j)
                            if not isinstance(value, str):
                                continue
                            try:
                                # If value contains already an absolute path,
                                # then it is not changed further.
                                path = Path(base_dir, value).resolve()
                            except RuntimeError:
                                # Don't fail with invalid entries.
                                continue
                            items.add(path)
                except (OSError, MemoryError):
                    continue
    return items
Ejemplo n.º 7
0
def findPV():
    'Find Paraview executable in the system. Under Windows (64bit only), this entails searching the registry (see `this post <http://www.paraview.org/pipermail/paraview/2010-August/018645.html>`__); under Linux, look in ``$PATH44 for executable called ``paraview``. Returns ``None`` is Paraview is not found.'
    import sys, operator
    if sys.platform == 'win32':
        # oh gee...
        # http://www.paraview.org/pipermail/paraview/2010-August/018645.html
        # - HKEY_CURRENT_USER\SOFTWARE\Wow6432Node\Kitware Inc.\ParaView 3.8.X (64bit machines single user install)
        # - HKEY_CURRENT_USER\SOFTWARE\Kitware Inc.\ParaView 3.8.X (32bit machines single user install)
        # - HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Kitware Inc.\ParaView 3.8.X (64bit machines all users)
        # - HKEY_LOCAL_MACHINE\SOFTWARE\Kitware Inc.\ParaView 3.8.X (32bit machines all users)
        #
        # we don't care about 32 bit, do just 64bit
        import winreg as winreg
        path = r'SOFTWARE\Wow6432Node\Kitware Inc.'
        paraviews = []
        for reg in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
            aReg = winreg.ConnectRegistry(None, reg)
            try:
                aKey = winreg.OpenKey(aReg,
                                      r'SOFTWARE\Wow6432Node\Kitware, Inc.')
            except WindowsError:
                continue
            for i in range(0, winreg.QueryInfoKey(aKey)[0]):
                keyname = winreg.EnumKey(aKey, i)
                if not keyname.startswith('ParaView '):
                    # print 'no match:',keyname
                    continue
                subKey = winreg.OpenKey(aKey, keyname)
                paraviews.append((keyname, subKey))
        # sort lexically using key name and use the last one (highest version)
        pv = sorted(paraviews, key=operator.itemgetter(1))
        if not pv:
            return None  # raise RuntimeError('ParaView installation not found in registry.')
        pvName, pvKey = pv[-1]
        pvExec = ''
        for i in range(0, winreg.QueryInfoKey(pvKey)[1]):
            key, val, T = winreg.EnumValue(pvKey, i)
            if key == '':
                pvExec = val + '/bin/paraview'
                break
        if not pvExec:
            return None  # raise RuntimeError('ParaView installation: found in registry, but default key is missing...?')
        return pvExec
    else:
        # on Linux, find it in $PATH
        import woo.utils
        return woo.utils.find_executable('paraview')
def Out_microphone():
    HTML_con.html_in("Выключение микрофона", 0)
    PATH = r"SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Capture"
    aKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, PATH, 0,
                          winreg.KEY_WOW64_64KEY + winreg.KEY_READ)
    try:
        for j in range(winreg.QueryInfoKey(aKey)[0]):
            new_Key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                     fr'{PATH}\{winreg.EnumKey(aKey,j)}', 0,
                                     winreg.KEY_WOW64_64KEY + winreg.KEY_READ)
            for i in range(winreg.QueryInfoKey(new_Key)[0]):
                try:
                    asubkey_name = winreg.EnumKey(new_Key, i)
                    asubkey = winreg.OpenKey(new_Key, asubkey_name)
                    val = winreg.QueryValueEx(
                        asubkey, "{a45c254e-df1c-4efd-8020-67d146a850e0},2")
                    if (('Microphone' in val) or ('Микрофон' in val)):
                        value_entry = ValueEntry(
                            winreg.HKEY_LOCAL_MACHINE,
                            fr"{PATH}\{winreg.EnumKey(aKey,j)}", "DeviceState",
                            winreg.REG_DWORD, 10000001)
                        Key_for_delete = winreg.OpenKey(
                            value_entry.root_key, value_entry.subkey, 0,
                            winreg.KEY_WOW64_64KEY + winreg.KEY_SET_VALUE +
                            winreg.KEY_READ)
                        winreg.SetValueEx(Key_for_delete, value_entry.name, 0,
                                          value_entry.data_type,
                                          value_entry.data)
                        logging.info(
                            f"Установка {repr(value_entry).replace('Параметр', 'параметра')}."
                        )
                        if (winreg.QueryValueEx(Key_for_delete,
                                                "DeviceState")[0] == 10000001):
                            HTML_con.html_in("Микрофон отключен.")  #10000001
                        else:
                            HTML_con.html_in("Микрофон не отключен.",
                                             Param=False)
                        winreg.CloseKey(Key_for_delete)
                except EnvironmentError as e:
                    pass
                except FileNotFoundError:
                    pass
    except WindowsError as e:
        logging.error(e)
        pass
    winreg.CloseKey(aKey)
    winreg.CloseKey(new_Key)
Ejemplo n.º 9
0
def foo(hive, flag):
    """Функция получения данных из реестра"""
    aReg = winreg.ConnectRegistry(None, hive)
    aKey = winreg.OpenKey(
        aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0,
        winreg.KEY_READ | flag)
    #print(aReg)
    count_subkey = winreg.QueryInfoKey(aKey)[0]
    software_list = []

    for i in range(count_subkey):
        software = {}
        try:
            asubkey_name = winreg.EnumKey(aKey, i)
            asubkey = winreg.OpenKey(aKey, asubkey_name)
            #print(asubkey_name)
            software['name'] = winreg.QueryValueEx(asubkey, "DisplayName")[0]
            try:
                software['version'] = winreg.QueryValueEx(
                    asubkey, "DisplayVersion")[0]
            except EnvironmentError:
                software['version'] = 'undefined'
            try:
                software['publisher'] = winreg.QueryValueEx(
                    asubkey, "Publisher")[0]
            except EnvironmentError:
                software['publisher'] = 'undefined'
            try:
                software['InstallLocation'] = winreg.QueryValueEx(
                    asubkey, "InstallLocation")[0]
                if software['InstallLocation'] == '' or software[
                        'InstallLocation'] == None:
                    software['InstallLocation'] = 'undefined'
            #except EnvironmentError:
            except:
                try:
                    software['InstallLocation'] = winreg.QueryValueEx(
                        asubkey, "InstallDir")[0]
                    if software['InstallLocation'] == '' or software[
                            'InstallLocation'] == None:
                        software['InstallLocation'] = 'undefined'
                except:
                    try:
                        software['InstallLocation'] = winreg.QueryValueEx(
                            asubkey, "DisplayIcon")[0]
                        if software['InstallLocation'] == '' or software[
                                'InstallLocation'] == None:
                            software['InstallLocation'] = 'undefined'
                    except:
                        software['InstallLocation'] = 'undefined'
            #try:
            #    software['InstallLocation'] = winreg.QueryValueEx(asubkey, "InstallLocation")[0]
            #except EnvironmentError:
            #    software['InstallLocation'] = 'undefined'
            software_list.append(software)
        except EnvironmentError:
            continue

    return software_list
Ejemplo n.º 10
0
    def windows(self):

        import winreg

        versionList = []
        # Open base key
        regkeys = (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE)
        for regkey in regkeys:
            base = winreg.ConnectRegistry(None, regkey)
            try:
                key = winreg.OpenKey(base, 'SOFTWARE\\Python\\PythonCore', 0,
                                     winreg.KEY_READ)
                break
            except:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                logging.error(
                    repr(
                        traceback.format_exception(exc_type, exc_value,
                                                   exc_traceback)))

        if key is not None:
            # Get info about subkeys
            nsub, nval, modified = winreg.QueryInfoKey(key)

            # Query Python versions from registry

            for i in range(nsub):
                try:
                    # Get name and subkey
                    name = winreg.EnumKey(key, i)
                    subkey = winreg.OpenKey(key, name + '\\InstallPath', 0,
                                            winreg.KEY_READ)
                    # Get install location and store
                    location = winreg.QueryValue(subkey, '')
                    versionList.append(os.path.normpath(location))
                    # Close
                    winreg.CloseKey(subkey)
                except:
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    logging.error(
                        repr(
                            traceback.format_exception(exc_type, exc_value,
                                                       exc_traceback)))

                # Close keys
                winreg.CloseKey(key)
                winreg.CloseKey(base)
        # Query Python versions from file system
        for rootname in ['C:/', 'C:/Program Files', 'C:/Program Files (x86)']:
            if not os.path.isdir(rootname):
                continue
            for dir_item in os.listdir(rootname):
                if dir_item.lower().startswith('python'):
                    path = os.path.normpath(os.path.join(rootname, dir_item))
                    if path not in versionList:
                        versionList.append(path)

        for path in versionList:
            yield path
Ejemplo n.º 11
0
def get_sessions():
    """
    Get PuTTY sessions as list(name)
    """
    reg_key = get_sessions_reg_key()
    num_keys, _, _ = winreg.QueryInfoKey(reg_key)

    return [winreg.EnumKey(reg_key, i) for i in range(num_keys)]
Ejemplo n.º 12
0
 def effacer_cle(self, nomCle):
     if self.si_existe_ruche(nomCle):
         subKey = self.get_registre(nomCle)
         nb_subk, nb_v, t = winreg.QueryInfoKey(subKey.key_handle)
         if (nb_subk > 0):
             for subkname in subKey.liste_sub_key(nb_subk):
                 subKey.effacer_cle(subkname)
         winreg.DeleteKey(self.key_handle, nomCle)
Ejemplo n.º 13
0
 def openConnection(self, key):
     '''
     Returns a connection string
     key     : a winreg key handle object        
     '''
     numValues = winreg.QueryInfoKey(key)[1]
     values = {winreg.EnumValue(key, i)[0]: winreg.EnumValue(key, i)[1] for i in range(numValues)}
     return '{}/{}@{}:{}/{}'.format(values['username'], values['password'], values['ip'], values['port'], values['service'])        
Ejemplo n.º 14
0
	def __init__(self):
		roots_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots")
		num_subkeys = winreg.QueryInfoKey(roots_key)[0]
		subkeys = list(map(lambda i: winreg.EnumKey(roots_key, i), range(num_subkeys)))
		self.latest_sdk = max(subkeys, key = lambda version_str: version_str.split(".")[2])
		self.bin_path = f"{winreg.QueryValueEx(roots_key, 'KitsRoot10')[0]}\\bin\\{self.latest_sdk}\\x64"
		self.dxc_path = f"{self.bin_path}\\dxc.exe"
		pass
Ejemplo n.º 15
0
def valuestodict(key):
    """Convert a registry key's values to a dictionary."""
    dict = {}
    size = winreg.QueryInfoKey(key)[1]
    for i in range(size):
        data = winreg.EnumValue(key, i)
        dict[data[0]] = data[1]
    return dict
Ejemplo n.º 16
0
 def Query(self):
     key=winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run')
     count=winreg.QueryInfoKey(key)[1]
     for i in range(count):
         name=winreg.EnumValue(key,i)[0]
         command=winreg.EnumValue(key,i)[1]
         self.tree.insert('',index='end',text=name,values=[command])
     winreg.CloseKey(key)
Ejemplo n.º 17
0
def _enum_registry_keys(key, sub_key):
    try:
        with reg.OpenKey(key, sub_key) as key:
            count = reg.QueryInfoKey(key)[0]
            for i in range(count):
                yield os.path.join(sub_key, reg.EnumKey(key, i))
    except OSError:
        return []
Ejemplo n.º 18
0
def suggest_javahome():
    if "JAVA_HOME" in os.environ:
        yield os.environ["JAVA_HOME"]

    java_bin = shutil.which("java")
    if java_bin:
        java_bin = os.path.realpath(java_bin)
        yield os.path.join(os.path.dirname(java_bin), "..")
        yield os.path.join(os.path.dirname(java_bin), "..", "jre")

    if is_win:
        import winreg
        java_key_paths = ('SOFTWARE\\JavaSoft\\JRE',
                          'SOFTWARE\\JavaSoft\\Java Runtime Environment',
                          'SOFTWARE\\JavaSoft\\JDK')
        for java_key_path in java_key_paths:
            looking_for = java_key_path
            try:
                kjava = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                       java_key_path)
                looking_for = java_key_path + "\\CurrentVersion"
                kjava_values = dict([
                    winreg.EnumValue(kjava, i)[:2]
                    for i in range(winreg.QueryInfoKey(kjava)[1])
                ])
                current_version = kjava_values['CurrentVersion']
                looking_for = java_key_path + '\\' + current_version
                kjava_current = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                               looking_for)
                kjava_current_values = dict([
                    winreg.EnumValue(kjava_current, i)[:2]
                    for i in range(winreg.QueryInfoKey(kjava_current)[1])
                ])
                yield kjava_current_values['JavaHome']
            except WindowsError as e:
                if e.errno == 2:
                    continue
                else:
                    raise

    if is_mac:
        try:
            result = subprocess.check_output(["/usr/libexec/java_home"])
            yield result.strip().decode("utf-8")
        except subprocess.CalledProcessError:
            yield "/System/Library/Frameworks/JavaVM.framework/Home"
Ejemplo n.º 19
0
    def test_create_sad(self):
        with subprocess.Popen(r'REG ADD ' + self.path,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE) as p:
            p.communicate()
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\testReg')
        mtime = datetime(1601, 1, 1) + timedelta(
            microseconds=winreg.QueryInfoKey(key)[2] // 10)
        winreg.CloseKey(key)
        f = open(r'c:\csvlog\csvlog.csv', "w")
        filewriter = csv.writer(f, delimiter=',')
        test = csv.DictWriter(f,
                              fieldnames=[
                                  'HostName', 'DateTime', 'IOCType', 'IOCPath',
                                  'OperationType', 'OpResult'
                              ])
        test.writeheader()
        f.close()
        f = open(r'c:\csvlog\csvlog.csv', 'a')
        writer = csv.writer(f)
        writer.writerow([
            '127.0.0.1',
            datetime.now() - timedelta(days=1), 'Registry', self.path,
            'Created', 'Completed'
        ])
        f.close()

        exec(self.pre_code)

        exec(self.post_code)

        try:

            with subprocess.Popen(r'REG QUERY ' + self.path,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE) as p:
                out, err = p.communicate()
                if not err:
                    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                         'Software\\testReg')
                    mtime2 = datetime(1601, 1, 1) + timedelta(
                        microseconds=winreg.QueryInfoKey(key)[2] // 10)
                    winreg.CloseKey(key)
                    self.assertTrue(mtime2 == mtime)
        except:
            self.assertFalse(True)
Ejemplo n.º 20
0
 def load(self, recursive=False):
     try:
         rootkey = winreg.OpenKey(self._keytype, self._keypath, 0,
                                  winreg.KEY_READ)
     except OSError:  # key doesn't exist
         return
     values = winreg.QueryInfoKey(rootkey)[1]
     for num in range(0, values):
         name, data, datatype = winreg.EnumValue(rootkey, num)
         try:
             SettingsBase.__setattr__(self, name, ast.literal_eval(data))
         except (ValueError, SyntaxError):
             raise SettingsError("Error")
     if recursive:
         keys, vals, mod = winreg.QueryInfoKey(rootkey)
         for i in range(0, keys):
             name = winreg.EnumKey(rootkey, i)
             s = Settings(parent=self, name=name, recursive=True)
Ejemplo n.º 21
0
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
Ejemplo n.º 22
0
    def get_registry_info():
        proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
        proc_arch64 = None if 'PROCESSOR_ARCHITEW6432' not in os.environ.keys() else os.environ['PROCESSOR_ARCHITEW6432'].lower()
        if proc_arch == 'x86' and not proc_arch64:
            arch_keys = {0}
        elif proc_arch == 'x86' or proc_arch == 'amd64':
            arch_keys = {winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY}
        else:
            raise OSError("Unhandled arch: %s" % proc_arch)

        for arch_key in arch_keys:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0, winreg.KEY_READ | arch_key)
            for i in range(0, winreg.QueryInfoKey(key)[0]):
                skey_name = winreg.EnumKey(key, i)
                skey = winreg.OpenKey(key, skey_name)
                try:
                    name = winreg.QueryValueEx(skey, 'DisplayName')[0]
                    stro = winreg.QueryValueEx(skey, 'UninstallString')[0]
                    packs = []
                    for regkey in ["URLInfoAbout", "InstallLocation", "Publisher"]:
                        try:
                           packs.append(winreg.QueryValueEx(skey, regkey)[0])
                        except:
                            packs.append(None)

                    url, loc, pub = packs

                    qstro = None
                    if 'MsiExec.exe' in stro:
                        qstro = stro + ' /quiet'
                    try:
                        qstro = winreg.QueryValueEx(skey, 'QuietUninstallString')[0]
                    except OSError as e:
                            pass
                    if qstro is not None:
                        gen_dict = {
                                    "DisplayName": name,
                                    "QuietUninstallString": qstro,
                                    "URLInfoAbout": url,
                                    "InstallLocation": loc,
                                    "Publisher": pub,
                                   }

                        keys.append(gen_dict)
                    else:
                        gen_dict = {
                                    "DisplayName": name,
                                    "UninstallString": stro,
                                    "URLInfoAbout": url,
                                    "InstallLocation": loc,
                                    "Publisher": pub,
                                   }
                        keys.append(gen_dict)
                except OSError as e:
                        pass
                finally:
                    skey.Close()
Ejemplo n.º 23
0
def initsysfonts_win32():
    """initialize fonts dictionary on Windows"""

    fontdir = join(os.environ.get('WINDIR', 'C:\\Windows'), 'Fonts')

    fonts = {}

    # add fonts entered in the registry

    # find valid registry keys containing font information.
    # http://docs.python.org/lib/module-sys.html
    # 0 (VER_PLATFORM_WIN32s)          Win32s on Windows 3.1
    # 1 (VER_PLATFORM_WIN32_WINDOWS)   Windows 95/98/ME
    # 2 (VER_PLATFORM_WIN32_NT)        Windows NT/2000/XP
    # 3 (VER_PLATFORM_WIN32_CE)        Windows CE
    if sys.getwindowsversion()[0] == 1:
        key_name = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts"
    else:
        key_name = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"
    key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key_name)

    for i in xrange_(_winreg.QueryInfoKey(key)[1]):
        try:
            # name is the font's name e.g. Times New Roman (TrueType)
            # font is the font's filename e.g. times.ttf
            name, font = _winreg.EnumValue(key, i)[0:2]
        except EnvironmentError:
            break

        # try to handle windows unicode strings for file names with
        # international characters
        if PY_MAJOR_VERSION < 3:
            # here are two documents with some information about it:
            # http://www.python.org/peps/pep-0277.html
            # https://www.microsoft.com/technet/archive/interopmigration/linux/mvc/lintowin.mspx#ECAA
            try:
                font = str(font)
            except UnicodeEncodeError:
                # MBCS is the windows encoding for unicode file names.
                try:
                    font = font.encode('MBCS')
                except UnicodeEncodeError:
                    # no success with str or MBCS encoding... skip this font.
                    continue

        if splitext(font)[1].lower() not in OpenType_extensions:
            continue
        if not dirname(font):
            font = join(fontdir, font)

        # Some are named A & B, both names should be processed separately
        # Ex: the main Cambria file is marked as "Cambria & Cambria Math"
        for name in name.split("&"):
            _parse_font_entry_win(name, font, fonts)

    return fonts
Ejemplo n.º 24
0
    def findPythonExecutables_win(self):
        import winreg

        # Open base key
        base = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
        try:
            key = winreg.OpenKey(base, 'SOFTWARE\\Python\\PythonCore', 0,
                                 winreg.KEY_READ)
        except Exception:
            return []

        # Get info about subkeys
        nsub, nval, modified = winreg.QueryInfoKey(key)

        # Query Python versions from registry
        versions = set()
        for i in range(nsub):
            try:
                # Get name and subkey
                name = winreg.EnumKey(key, i)
                subkey = winreg.OpenKey(key, name + '\\InstallPath', 0,
                                        winreg.KEY_READ)
                # Get install location and store
                location = winreg.QueryValue(subkey, '')
                versions.add(location)
                # Close
                winreg.CloseKey(subkey)
            except Exception:
                pass

        # Close keys
        winreg.CloseKey(key)
        winreg.CloseKey(base)

        # Query Python versions from file system
        for rootname in [
                'c:/', 'C:/program files/', 'C:/program files (x86)/'
        ]:
            if not os.path.isdir(rootname):
                continue
            for dname in os.listdir(rootname):
                if dname.lower().startswith('python'):
                    versions.add(os.path.join(rootname, dname))

        # Normalize all paths, and remove trailing backslashes
        versions = set([os.path.normcase(v).strip('\\') for v in versions])

        # Append "python.exe" and check if that file exists
        versions2 = []
        for dname in sorted(versions, key=lambda x: x[-2:]):
            exename = os.path.join(dname, 'python.exe')
            if os.path.isfile(exename):
                versions2.append(exename)

        # Done
        return versions2
Ejemplo n.º 25
0
def _get_win_simnibs_env_vars():
    ''' 'Creates a disctionary with environment names and values '''
    simnibs_env_vars = {}
    with winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment') as reg:
        _, num_values, _ = winreg.QueryInfoKey(reg)
        for i in range(num_values):
            var_name, value, _ = winreg.EnumValue(reg, i)
            if 'SIMNIBS' in var_name:
                simnibs_env_vars[var_name] = value
    return simnibs_env_vars
Ejemplo n.º 26
0
def read_opt_timout():
    key = winreg.OpenKey(
        winreg.HKEY_CURRENT_USER,
        "Software\Classes\Jupyter.nbopen_windows\shell\open\command", 0,
        winreg.KEY_READ)
    for i in range(0, winreg.QueryInfoKey(key)[1]):
        v = winreg.EnumValue(key, i)
        if v[0].lower() == "timeout":
            return float(v[1])
    return 1
Ejemplo n.º 27
0
def get_windows_software():
    """
    从注册表获取Windows系统安装的软件列表
    :return:
    """
    import winreg

    # 需要遍历的两个注册表
    sub_keys = [
        r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
        r'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall',
    ]

    software_list = {}

    # 连接注册表根键
    regRoot = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    for sub_key in sub_keys:
        keyHandle = winreg.OpenKey(regRoot, sub_key, 0, winreg.KEY_ALL_ACCESS)
        # 获取该目录下所有键的个数(0-下属键个数;1-当前键值个数)
        for i in range(winreg.QueryInfoKey(keyHandle)[0]):
            try:
                # 穷举每个键,获取键名
                key_name = winreg.EnumKey(keyHandle, i)
                key_path = f"{sub_key}\\{key_name}"
                # 根据获取的键名拼接之前的路径作为参数,获取当前键下所属键的控制
                each_key = winreg.OpenKey(regRoot, key_path, 0, winreg.KEY_ALL_ACCESS)
                if winreg.QueryInfoKey(each_key)[1] > 1:
                    # 穷举每个键,获取键名、键值以及数据类型
                    # name, value, type = winreg.EnumValue(each_key, j)
                    # print(name,value,type)
                    DisplayName, REG_SZ = winreg.QueryValueEx(each_key, 'DisplayName')
                    DisplayVersion, REG_SZ = winreg.QueryValueEx(each_key, 'DisplayVersion')
                    software_list[DisplayName] = DisplayVersion
            except WindowsError as e:
                pass
            finally:
                winreg.CloseKey(each_key)

    winreg.CloseKey(keyHandle)
    winreg.CloseKey(regRoot)

    return software_list
Ejemplo n.º 28
0
def get_first_attached_date(device_class_guid, instance_id):
    """
        Get the first time a USB drive was attached to the system.
        @param device_class_guid: The device guid.
        @param instance_id: Device serial number or instance id.
    """
    path = "SYSTEM\\CurrentControlSet\\Control\\DeviceClasses\\{0}".format(device_class_guid)

    with reg.OpenKeyEx(reg.HKEY_LOCAL_MACHINE, path) as key:
        # Iterate over the registry keys.
        for key_inx in range(reg.QueryInfoKey(key)[0]):
            key_name = reg.EnumKey(key, key_inx)

            if (device_class_guid in key_name) and (instance_id in key_name):
                # Open the device registry key.
                with reg.OpenKeyEx(key, key_name) as device_key:
                    # Store last accessed time.
                    windows_time = reg.QueryInfoKey(device_key)[2]
                    return utils.get_time(windows_time)
Ejemplo n.º 29
0
def get_session(name):
    """
    Get PuTTY session
    """
    reg_key = get_session_reg_key(name)

    _, num_values, _ = winreg.QueryInfoKey(reg_key)

    return [[name, value] for name, value, _ in [\
        winreg.EnumValue(reg_key, i) for i in range(num_values)]]
Ejemplo n.º 30
0
 def versions() -> list:
     installed_versions = []
     with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                         r'SOFTWARE\Adobe\Photoshop') as hKey:
         # Get the information about the key.
         subkey_count, values_count, modtime = winreg.QueryInfoKey(hKey)
         installed_versions_count = subkey_count
         for version in range(installed_versions_count):
             installed_versions.append(winreg.EnumKey(hKey, version))
         return installed_versions