Ejemplo n.º 1
0
 def run(self):
     required_files = [cell_profiler_setup_path]
     try:
         key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                               "SOFTWARE\Microsoft\Microsoft SDKs\Windows")
         best_sdk = _winreg.EnumKey(key, _winreg.QueryInfoKey(key)[0] - 1)
         sdk_key = _winreg.OpenKey(key, best_sdk)
         key.Close()
         signtool = os.path.join(
             _winreg.QueryValueEx(sdk_key, "InstallationFolder")[0], "Bin",
             "signtool.exe")
         sdk_key.Close()
         assert (os.path.isfile(signtool))
     except:
         raise distutils.errors.DistutilsExecError, \
               "The Microsoft Windows SDK does not seem to be properly installed"
     self.execute(subprocess.check_call, ([
         signtool, "sign", "/a", "/du", "http://www.cellprofiler.org/",
         "/t", "http://timestamp.comodoca.com/authenticode",
         cell_profiler_setup_path
     ], ), "Signing %s" % cell_profiler_setup)
Ejemplo n.º 2
0
Archivo: winreg.py Proyecto: moepnse/pi
    def get_keys(self):

        key_handle = winreg.OpenKey(REG_MAPPING[self._key], self._sub_key)

        # winreg.QueryInfoKey:
        # Returns information about a key, as a tuple.
        #
        # Index     Meaning
        # 0         An integer giving the number of sub keys this key has.
        # 1         An integer giving the number of values this key has.
        # 2         An integer giving when the key was last modified (if available) as 100?s of nanoseconds since Jan 1, 1600.
        key_count = winreg.QueryInfoKey(self._key_handle)[0]
        for i in range(0, key_count):

            # winreg.EnumKey:
            # Enumerates values of an open registry key, returning a tuple.
            #
            # The result is the name of a key
            key_name = winreg.EnumKey(self._key_handle, i)

            yield Key(self._key, self._sub_key, key_name)
Ejemplo n.º 3
0
 def getApplications(self):
     retval = set()
     key_path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
     for view_flag in (KEY_WOW64_32KEY, KEY_WOW64_64KEY):
         rootkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key_path, 0,
                                   view_flag | _winreg.KEY_READ)
         items = _winreg.QueryInfoKey(rootkey)[0]
         for idx in range(items):
             cur_key_path = _winreg.EnumKey(rootkey, idx)
             cur_key = _winreg.OpenKey(rootkey, cur_key_path, 0,
                                       view_flag | _winreg.KEY_READ)
             try:
                 if self._is_item_update(cur_key):
                     continue
                 display_name = QueryStringValue(cur_key, u'DisplayName')
                 if len(display_name) == 0:
                     continue
                 retval.add(display_name)
             except:
                 pass
     return list(retval)
Ejemplo n.º 4
0
def get_all_exe():
    sub_key = [r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
               r'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall']

    software_name = []

    for i in sub_key:
        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, i, 0, _winreg.KEY_ALL_ACCESS)
        for j in range(0, _winreg.QueryInfoKey(key)[0] - 1):
            try:
                key_name = _winreg.EnumKey(key, j)
                key_path = i + '\\' + key_name
                each_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key_path, 0, _winreg.KEY_ALL_ACCESS)
                DisplayName, REG_SZ = _winreg.QueryValueEx(each_key, 'DisplayName')
                DisplayName = DisplayName.encode('utf-8')
                software_name.append(DisplayName)
            except WindowsError:
                pass

    software_name = sorted(set(software_name))
    return software_name
Ejemplo n.º 5
0
 def retrieve_info(self, hkey, name_key):
     values = {}
     num = winreg.QueryInfoKey(hkey)[1]
     for x in range(0, num):
         k = winreg.EnumValue(hkey, x)
         if 'password' in k[0].lower():
             try:
                 password = win.Win32CryptUnprotectData(
                     k[1][1:],
                     is_current_user=constant.is_current_user,
                     user_dpapi=constant.user_dpapi)
                 values[k[0]] = password.decode('utf16')
             except Exception as e:
                 self.debug(str(e))
                 values[k[0]] = 'N/A'
         else:
             try:
                 values[k[0]] = str(k[1]).decode('utf16')
             except Exception:
                 values[k[0]] = str(k[1])
     return values
Ejemplo n.º 6
0
def find_ldxcmd():
    if sys.platform.startswith("win"):
        # Read from SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
        # Setting security access mode. KEY_WOW64_64KEY is used for 64-bit TDE
        sam = _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY
        reg_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0,
                                  sam)
        latest_version = ""
        latest_build = 0
        path_to_latest_build = ""
        # iterate through all subkeys of \Uninstall
        for i in xrange(0, _winreg.QueryInfoKey(reg_key)[0]):
            try:
                subkey = _winreg.EnumKey(reg_key, i)
                if re.match(WINDOWS_GUID_RX, subkey):
                    tde_key = _winreg.OpenKey(reg_key, subkey)
                    display_name = str(_winreg.QueryValueEx(tde_key, "DisplayName")[0])
                    if display_name.startswith("Load DynamiX TDE"):
                        display_version = str(_winreg.QueryValueEx(tde_key, "DisplayVersion")[0])
                        match = re.match("(\d+).(\d+).(\d+)", display_version)
                        if match:
                            tde_build = int(match.group(3))
                            if tde_build > latest_build:
                                path_to_build = str(_winreg.QueryValueEx(tde_key, "InstallLocation")[0])
                                path_to_build = os.path.join(path_to_build, "LdxCmd.exe")
                                if os.path.exists(path_to_build):
                                    latest_version = display_version
                                    latest_build = tde_build
                                    path_to_latest_build = path_to_build
            except EnvironmentError:
                break
        if latest_build > 0:
            print ("The latest LdxCmd version found: " + latest_version)
            return path_to_latest_build
        else:
            raise Exception('LdxCmd.exe not found.')
    else:
        if not os.path.exists("/opt/swifttest/resources/dotnet/LdxCmd"):
            raise Exception('LdxCmd executable not found: /opt/swifttest/resources/dotnet/LdxCmd')
        return "/opt/swifttest/resources/dotnet/LdxCmd"
Ejemplo n.º 7
0
def Get_User_ShellFolders():
    # Routine to grab all the Windows Shell Folder locations from the registry.  If successful, returns dictionary
    # of shell folder locations indexed on Windows keyword for each; otherwise, returns an empty dictionary.
    import _winreg
    return_dict = {}

    # First open the registry hive
    try:
        Hive = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
    except WindowsError:
        print "Can't connect to registry hive HKEY_CURRENT_USER."
        return return_dict

    # Then open the registry key where Windows stores the Shell Folder locations
    try:
        Key = _winreg.OpenKey(
            Hive,
            "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
    except WindowsError:
        print "Can't open registry key Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders."
        _winreg.CloseKey(Hive)
        return return_dict

    # Nothing failed above, so enumerate through all the Shell Folder values and return in a dictionary
    # This relies on error at end of
    try:
        #i = 0
        #while 1:
        for i in range(0, _winreg.QueryInfoKey(Key)[1]):
            name, value, val_type = _winreg.EnumValue(Key, i)
            return_dict[name] = value
            i += 1
        _winreg.CloseKey(Key)  # Only use with for loop
        _winreg.CloseKey(Hive)  # Only use with for loop
        return return_dict  # Only use with for loop
    except WindowsError:
        # In case of failure before read completed, don't return partial results
        _winreg.CloseKey(Key)
        _winreg.CloseKey(Hive)
        return {}
Ejemplo n.º 8
0
def get_reboot_required():
  """Returns True if the system should be rebooted to apply updates.

  This is not guaranteed to notice all conditions that could require reboot.
  """
  # Based on https://stackoverflow.com/a/45717438
  k = None
  import _winreg
  try:
    k = _winreg.OpenKey(
        _winreg.HKEY_LOCAL_MACHINE,
        'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\'
        'Auto Update\\RebootRequired')
    _, num_values, _ = _winreg.QueryInfoKey(k)
    return num_values > 0
  except WindowsError:  # pylint: disable=undefined-variable
    # This error very likely means the RebootRequired key does not exist,
    # meaning reboot is not required.
    return False
  finally:
    if k:
      k.Close()
    def find_services_trigger(self, service):
        access_write = KEY_WRITE | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE
        hkey = OpenKey(HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Tracing', 0,
                       access_write)
        num = winreg.QueryInfoKey(hkey)[0]

        triggers = []
        for x in range(0, num):
            svc = winreg.EnumKey(hkey, x)
            for s in service:
                if s.name.lower() == svc.lower() and s.permissions['start']:
                    is_service_running = self.is_service_running(svc)
                    if not is_service_running or (is_service_running
                                                  and s.permissions['stop']):
                        triggers.append(s)
                        print('[+] Service {name} found'.format(name=s.name))
                    else:
                        print(
                            '[-] Service {name} already running and could not be stopped'
                            .format(name=s.name))
        winreg.CloseKey(hkey)
        return triggers
Ejemplo n.º 10
0
    def _recursive_delete(self, key0, key1, key2=''):
        """ Delete a key and its subkeys. """

        current = key1 if not key2 else key1 + '\\' + key2
        with _winreg.OpenKey(key0, current, 0, _winreg.KEY_ALL_ACCESS) as key:
            info = _winreg.QueryInfoKey(key)
            for x in range(info[0]):
                """
                Deleting the subkey will change the SubKey count used by EnumKey.
                We must always pass 0 to EnumKey so we always get back the new
                first SubKey.
                """
                subkey = _winreg.EnumKey(key, 0)
                try:
                    _winreg.DeleteKey(key, subkey)
                except WindowsError:
                    self._recursive_delete(key0, current, key2=subkey)

        try:
            _winreg.DeleteKey(key0, key1)
        except WindowsError:
            pass
Ejemplo n.º 11
0
    def retrieve_softwares(self):
        results = []

        # Open the Base on read only
        accessRead = KEY_READ | KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE

        # check the uninstall key path
        hkey = _winreg.OpenKey(
            HKEY_LOCAL_MACHINE,
            "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\\", 0,
            accessRead)
        num = _winreg.QueryInfoKey(hkey)[0]

        # loop through number of subkeys
        for x in range(0, num):

            # Name of the software key
            sk = _winreg.EnumKey(hkey, x)

            # ------ Check if the key has his executable with write access and the folder containing it as well ------
            try:
                skey = _winreg.OpenKey(hkey, sk, 0, accessRead)

                name = str(_winreg.QueryValueEx(skey, "DisplayName")[0])
                if name:
                    # regex to not match security patch (KB)
                    m = re.match(r".*KB[0-9]{5,7}.*", name, re.IGNORECASE)
                    if not m:
                        soft = Software()
                        soft.name = name
                        soft.version = str(
                            _winreg.QueryValueEx(skey, "DisplayVersion")[0])
                        soft.key = skey
                        results.append(soft)
            except:
                pass

        return results
Ejemplo n.º 12
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 fonts are
returned by default with AFM fonts as an option.
"""

    import _winreg
    if directory is None:
        directory = win32FontDirectory()

    key, items = None, {}
    for fontdir in MSFontDirectories:
        try:
            local = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, fontdir)
        except OSError:
            continue

        if not local:
            return glob.glob(os.path.join(directory, '*.'+fontext))
        try:
            for j in range(_winreg.QueryInfoKey(local)[1]):
                try:
                    key, direc, any = _winreg.EnumValue( local, j)
                    if not os.path.dirname(direc):
                        direc = os.path.join(directory, direc)
                    direc = os.path.abspath(direc).lower()
                    if direc[-4:] == '.'+fontext:
                        items[direc] = 1
                except EnvironmentError:
                    continue
                except WindowsError:
                    continue
                        
            return items.keys()
        finally:
            _winreg.CloseKey(local)
    return None
Ejemplo n.º 13
0
    def run(self):
        if float(win.get_os_version()) > 6.1:
            self.debug(u'Internet Explorer passwords are stored in Vault (check vault module)')
            return

        pwd_found = []
        try:
            hkey = win.OpenKey(win.HKEY_CURRENT_USER, 'Software\\Microsoft\\Internet Explorer\\IntelliForms\\Storage2')
        except Exception:
            self.debug(traceback.format_exc())
        else:
            nb_site = 0
            nb_pass_found = 0

            # retrieve the urls from the history
            hash_tables = self.get_hash_table()

            num = winreg.QueryInfoKey(hkey)[1]
            for x in range(0, num):
                k = winreg.EnumValue(hkey, x)
                if k:
                    nb_site += 1
                    for h in hash_tables:
                        # both hash are similar, we can decipher the password
                        if h[1] == k[0][:40].lower():
                            nb_pass_found += 1
                            cipher_text = k[1]
                            pwd_found += self.decipher_password(cipher_text, h[0])
                            break

            winreg.CloseKey(hkey)

            # manage errors
            if nb_site > nb_pass_found:
                self.error(u'%s hashes have not been decrypted, the associate website used to decrypt the '
                           u'passwords has not been found' % str(nb_site - nb_pass_found))

        return pwd_found
Ejemplo n.º 14
0
def getInstalledRegvalnameVersion(d):
    """Get the version of the installed package from a registry value.

    Use the information specified in the package d to lookup the installed
    version on the computer.

    @param d A installversion dictionary entry for a package containing at
    least entries for 'key', 'subkey', 'regex', and 'regexpos'
    @return The version installed or None.
    """
    try:
        # should do a lookup table here
        if d['key'] == 'HKLM':
            tempkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, d['subkey'])
        else:
            return None
        vals = _winreg.QueryInfoKey(tempkey)[1]
        valnames = [_winreg.EnumValue(tempkey, i)[0] for i in xrange(vals)]
        valnames = sorted(valnames)
        valnamesstr = "\n".join(valnames)
        version = re.findall(d['regex'], valnamesstr)[d['regexpos']]
        return version
    except TypeError as strerror:
        if strerror == 'first argument must be a string or compiled pattern':
            print 'you are missing or have an invalid regex in %s' % d
        elif strerror == 'expected string or buffer':
            print 'your have no value being pulled from the registry'
        print 'when calling getInstalledRegvalnameVersion(%s)' % d
    except WindowsError:
        print 'The registry key or value could not be found'
        print 'when calling getInstalledRegvalnameVersion(%s)' % d
    except KeyError as strerror:
        print 'd did not contain a "%s" entry' % strerror
        print 'when calling getInstalledRegvalnameVersion(%s)' % d
    except:
        print 'unkown error running getInstalledRegvalnameVersion(%s)' % d
    else:
        return None
Ejemplo n.º 15
0
def unregister(name, versions=_reg_versions):
    """remove an from excels startup list"""
    # need to add a _d if we are debugging?
    basename = "%s.xll" % name.replace('.', os.sep)
    _log.info('Looking to unregister %s' % basename)

    for version in versions:
        key_name = _reg_key % {'version': version}

        try:
            key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key_name, 0,
                                  _winreg.KEY_READ | _winreg.KEY_WRITE)
        except WindowsError:
            _log.debug('Could not find %s' % key_name)
            continue

        # get count of keys to consder
        _, count, _ = _winreg.QueryInfoKey(key)

        # loop over all values in the register
        names = []
        for i in xrange(count):
            name, value, type = _winreg.EnumValue(key, i)

            if type != _winreg.REG_SZ or not name.startswith('OPEN'):
                continue

            # remove quotes
            value = value.strip('"')

            # clear up anything with _xltypes.pyd, what about _xltypes_d.pyd?
            if value.endswith(basename):
                names.append(name)

        for name in names:
            _log.info("ExcelXLLSDK.register.unregister: %s\\%s = %s" %
                      (key_name, name, value))
            _winreg.DeleteValue(key, name)
Ejemplo n.º 16
0
def find_cortana():
    index = 0
    cortana_version = []

    try:
        key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
                              "Software\Classes\ActivatableClasses\Package", 0,
                              _winreg.KEY_READ)
    except Exception as error:
        print_error(
            "Unable to open registry key, exception was raised: {}".format(
                error))
        return False

    try:
        num = _winreg.QueryInfoKey(key)[0]
        for x in range(0, num):
            if "Microsoft.Windows.Cortana_" in _winreg.EnumKey(key, x):
                cortana_version.append(_winreg.EnumKey(key, x))
                break
    except WindowsError as error:
        pass
    return cortana_version
Ejemplo n.º 17
0
def deregister_file_extension(ext):
    """Remove ourselves as the default handler for the file extension, setting
    the first available alternative handler if found."""
    openkeys = []
    replacement = ""
    try:    
        try:
            key = _winreg.OpenKeyEx(_winreg.HKEY_CLASSES_ROOT,"%s\\OpenWithProgIds" % ext,0,_winreg.KEY_QUERY_VALUE)
            openkeys.insert(0,key)
            for i in range(0,_winreg.QueryInfoKey(key)[1]):
                value = _winreg.EnumValue(key,i)[0]
                if value and value != "Juice%s" % ext:
                    replacement = value   
            key = _winreg.OpenKeyEx(_winreg.HKEY_CLASSES_ROOT,ext,0,_winreg.KEY_ALL_ACCESS)
            openkeys.insert(0,key)
            _winreg.SetValueEx(key,"",0,_winreg.REG_SZ,replacement)
        finally:
            for key in openkeys:
                _winreg.CloseKey(key)
    except WindowsError, e:
        errno, message = e.args
        if errno != 2:
            raise e
Ejemplo n.º 18
0
    def serialports_GET(self):
        try:
            serialports = []

            if os.name == 'nt':
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                     'HARDWARE\\DEVICEMAP\\SERIALCOMM')
                for i in range(winreg.QueryInfoKey(key)[1]):
                    try:
                        val = winreg.EnumValue(key, i)
                    except:
                        pass
                    else:
                        if val[0].find('VCP') > -1:
                            serialports.append(str(val[1]))
            elif os.name == 'posix':
                serialports = glob.glob('/dev/ttyUSB*')

            serialports.sort()

            return {'serialports': serialports}
        except Exception as err:
            return ['Could not scan for serial port. Error={0}'.format(err)]
Ejemplo n.º 19
0
def win32_find_myo_port():
    path = 'SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_2458&PID_0001\\1\\Device Parameters'
    key = None
    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        info = winreg.QueryInfoKey(key)
        values_count = info[1]
        i = 0
        while (i < values_count):
            val = winreg.EnumValue(key,
                                   i)  #(keyname, value, type), type 1: REG_SZ
            if val[0] == 'PortName':  # That's the keyname we are interested in
                portname = val[1]
                winreg.CloseKey(key)
                return portname
            # else continue with loop
        # If loop ended, we don't have PortName
        winreg.CloseKey(key)
        return None
    except WindowsError:
        if key is not None:
            winreg.CloseKey(key)
        return None
Ejemplo n.º 20
0
def disable_proxy():
    _, values_num, _ = winreg.QueryInfoKey(CONNECTIONS)
    for i in range(0, values_num):
        key, value, _ = winreg.EnumValue(CONNECTIONS, i)

        List = INTERNET_PER_CONN_OPTION_LIST()
        Option = (INTERNET_PER_CONN_OPTION * 1)()
        nSize = c_ulong(sizeof(INTERNET_PER_CONN_OPTION_LIST))

        Option[0].dwOption = INTERNET_PER_CONN_FLAGS
        Option[0].Value.dwValue = PROXY_TYPE_DIRECT

        List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST)
        List.pszConnection = create_unicode_buffer(key)
        List.dwOptionCount = 1
        List.dwOptionError = 0
        List.pOptions = Option

        InternetSetOption(None, INTERNET_OPTION_PER_CONNECTION_OPTION,
                          byref(List), nSize)

    InternetSetOption(None, INTERNET_OPTION_SETTINGS_CHANGED, None, 0)
    InternetSetOption(None, INTERNET_OPTION_REFRESH, None, 0)
Ejemplo n.º 21
0
 def retrieve_info(self, hkey, name_key):
     values = {}
     num = winreg.QueryInfoKey(hkey)[1]
     for x in range(0, num):
         k = winreg.EnumValue(hkey, x)
         if 'password' in k[0].lower():
             try:
                 password_bytes = win.Win32CryptUnprotectData(k[1][1:], is_current_user=constant.is_current_user, user_dpapi=constant.user_dpapi)
                 #  password_bytes is <password in utf-16> + b'\x00\x00'
                 terminator = b'\x00\x00'
                 if password_bytes.endswith(terminator):
                     password_bytes = password_bytes[: -len(terminator)]
                 
                 values[k[0]] = password_bytes.decode("utf-16")
             except Exception as e:
                 self.debug(str(e))
                 values[k[0]] = 'N/A'
         else:
             try:
                 values[k[0]] = str(k[1]).decode('utf16')
             except Exception:
                 values[k[0]] = str(k[1])
     return values
Ejemplo n.º 22
0
 def _get_addresses_of_proxy_pac(self):
     """
     Return a list of possible auto proxy .pac files being used,
     based on the system registry (win32) or system preferences (OSX).
     @return: list of urls
     """
     pac_files = []
     if sys.platform == 'win32':
         try:
             import _winreg as winreg  # used from python 2.0-2.6
         except:
             import winreg  # used from python 2.7 onwards
         net = winreg.OpenKey(
             winreg.HKEY_CURRENT_USER,
             "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
         )
         n_subs, n_vals, last_mod = winreg.QueryInfoKey(net)
         subkeys = {}
         for i in range(n_vals):
             this_name, this_val, this_type = winreg.EnumValue(net, i)
             subkeys[this_name] = this_val
         if 'AutoConfigURL' in subkeys.keys() and len(
                 subkeys['AutoConfigURL']) > 0:
             pac_files.append(subkeys['AutoConfigURL'])
     elif sys.platform == 'darwin':
         import plistlib
         sys_prefs = plistlib.readPlist(
             '/Library/Preferences/SystemConfiguration/preferences.plist')
         networks = sys_prefs['NetworkServices']
         # loop through each possible network (e.g. Ethernet, Airport...)
         for network in networks.items():
             # the first part is a long identifier
             net_key, network = network
             if 'ProxyAutoConfigURLString' in network['Proxies'].keys():
                 pac_files.append(
                     network['Proxies']['ProxyAutoConfigURLString'])
     return list(set(pac_files))  # remove redundant ones
Ejemplo n.º 23
0
 def GetInstalledBrowsers(self):
     '''
     usage:object.GetInstalledBrowsers()
     Output:
     
     browser_list-->list
     '''
     path = 'SOFTWARE\Clients\StartMenuInternet'
     Hkeys = reg.HKEY_LOCAL_MACHINE
     Regkey = reg.ConnectRegistry(None, Hkeys)
     key = reg.OpenKey(Regkey, path, 0, reg.KEY_READ | reg.KEY_WOW64_32KEY)
     key_count = reg.QueryInfoKey(key)[0]
     browser = {}
     browser_list = []
     for i in range(key_count):
         singsoft = {}
         try:
             keyname = reg.EnumKey(key, i)
             singsoft['id'] = i
             singsoft['Name'] = keyname
             browser_list.append(singsoft)
         except Exception as ex:
             continue
     return browser_list
Ejemplo n.º 24
0
def get_ghostscript_dir():
    """
    Tries to determine the directory in which ghostscript is installed. If successful the path is
    returned. If nothing is found the function returns None.

    The function searches the Windows registry under HKLM an HKCU for the keys defined in the list
    STR_KEYS_GHOSTSCRIPT. If a key is found it iterates over all available subkeys found under the
    key and checks if they contain the directory.
    """

    for access_right in _REG_ACCESS_RIGHTS:
        for hkey in [_wr.HKEY_LOCAL_MACHINE, _wr.HKEY_CURRENT_USER]:
            for str_key in _STR_KEYS_GHOSTSCRIPT:
                try:
                    key = _wr.OpenKey(hkey, str_key, 0, access_right)

                    # Ghostscript stores the information in a subkey the name
                    # of which is the installed version number. If several
                    # subkeys are found we iterate over them until we find a
                    # valid directory
                    num_subkeys = _wr.QueryInfoKey(key)[0]
                    for i in range(0, num_subkeys):
                        subkey_str = _wr.EnumKey(key, i)
                        subkey = _wr.OpenKeyEx(key, subkey_str)
                        dirname = _wr.QueryValue(subkey, None) + r'\bin'
                        _wr.CloseKey(subkey)
                        _wr.CloseKey(key)
                        if _os.path.isdir(dirname):
                            return dirname
                except WindowsError:
                    pass

    _set_last_error(
        'Path to ghostscript not found (%s not found in registry!)' %
        _STR_KEYS_GHOSTSCRIPT)
    return None
Ejemplo n.º 25
0
    def getSoftWares(self):
        #try:
        keyX = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                               'Software\\Autodesk\\Maya')
        for item in range(0, _winreg.QueryInfoKey(keyX)[0]):
            version = _winreg.EnumKey(keyX, item)
            temp = ('Software\\Autodesk\\Maya\\' + version +
                    '\\Setup\\InstallPath\\')
            try:
                keyX1 = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, temp)
                path = _winreg.QueryValueEx(keyX1, 'MAYA_INSTALL_LOCATION')[0]

                radioButton = QtGui.QRadioButton(self.groupBox)
                radioButton.setObjectName('maya' + version)
                radioButton.setText('maya' + version)
                radioButton.accessibleName = path
                radioButton.setChecked(False)
                radioButton.clicked.connect(
                    functools.partial(self.getPlugIns, version))
                self.gridLayout.addWidget(radioButton, item / 2, item % 2, 1,
                                          1)

            except WindowsError:
                pass
Ejemplo n.º 26
0
def listRegKeyValues(registry, key, architecture=None):
    """ Returns a list of child keys and their values as tuples.
	
	Each tuple contains 3 items.
		- A string that identifies the value name
		- An object that holds the value data, and whose type depends on the underlying registry type
		- An integer that identifies the type of the value data (see table in docs for _winreg.SetValueEx)
	
	Args:
		registry (str): The registry to look in. 'HKEY_LOCAL_MACHINE' for example
		key (str): The key to open. r'Software\Autodesk\Softimage\InstallPaths' for example
		architecture (int | None): 32 or 64 bit. If None use system default. Defaults to None
	
	Returns:
		List of tuples
	"""
    import _winreg
    regKey = getRegKey(registry, key, architecture=architecture)
    ret = []
    if regKey:
        subKeys, valueCount, modified = _winreg.QueryInfoKey(regKey)
        for index in range(valueCount):
            ret.append(_winreg.EnumValue(regKey, index))
    return ret
Ejemplo n.º 27
0
def printinfo():
	print 'version 1.2 modified'
	print 'Registry Info:'
	hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,r'System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\')
	keyInfo = _winreg.QueryInfoKey(hkey)
	for index in range(keyInfo[0]):
			hSubKeyName = _winreg.EnumKey(hkey, index)
				
			print hSubKeyName
			hSubKey = _winreg.OpenKey(hkey, hSubKeyName)
			try:
				print _winreg.QueryValueEx(hSubKey, 'NameServer')
			except:
				pass
	print 'WMI Info'
	wmiService = wmi.WMI()
	colNicConfigs = wmiService.Win32_NetworkAdapterConfiguration()
	for i in range(len(colNicConfigs)):
		print 'IPEnabled'
		print colNicConfigs[i].IPEnabled
		print 'SettingID' 
		print colNicConfigs[i].SettingID 
		print 'DNS' 
		print colNicConfigs[i].DNSServerSearchOrder
Ejemplo n.º 28
0
def findSerialPorts():
    '''
    Returns the serial ports of the motes connected to the computer.
    
    :returns: A list of tuples (name,baudrate) where:
        - name is a strings representing a serial port, e.g. 'COM1'
        - baudrate is an int representing the baurate, e.g. 115200
    '''
    serialports = []
    
    if os.name=='nt':
        path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
        for i in range(winreg.QueryInfoKey(key)[1]):
            try:
                val = winreg.EnumValue(key,i)
            except:
                pass
            else:
                if   val[0].find('VCP')>-1:
                    serialports.append( (str(val[1]),BAUDRATE_TELOSB) )
                elif val[0].find('Silabser')>-1:
                    serialports.append( (str(val[1]),BAUDRATE_GINA) )
                elif val[0].find('ProlificSerial')>-1:
                    serialports.append( (str(val[1]),BAUDRATE_WSN430) )
    elif os.name=='posix':
        if platform.system() == 'Darwin':
            portMask = '/dev/tty.usbserial-*'
        else:
            portMask = '/dev/ttyUSB*'
        serialports = [(s,BAUDRATE_GINA) for s in glob.glob(portMask)]
    
    # log
    log.info("discovered following COM port: {0}".format(['{0}@{1}'.format(s[0],s[1]) for s in serialports]))
    
    return serialports
Ejemplo n.º 29
0
def list_reg_key_values(registry, key, architecture=None):
    """
    Returns a list of child keys and their values as tuples containing:
        - A string that identifies the value name
        - An object that holds the value data, and whose type depends on the underlying registry type
        - An integer that identifies the type of the value data (see table in docs for _winreg.SetValueEx)
    :param registry: str, registry to look in. HKEY_LOCAL_MACHINE for example
    :param key: str, key to open 'Software/Ubisoft/Test' for example
    :param architecture: variant, int || None, 32 or 64 bit. If None, default system architecture is used
    :return: list<tuple>
    """

    import _winreg

    reg_key = get_reg_key(registry=registry,
                          key=key,
                          architecture=architecture)
    ret = list()
    if reg_key:
        sub_keys, value_count, modified = _winreg.QueryInfoKey(reg_key)
        for i in range(value_count):
            ret.append(_winreg.EnumValue(reg_key, i))

    return ret
def AutoReadMoldexVersion():
    # Read the Moldex3D installing address
    pyHKEY = _winreg.OpenKey(
        _winreg.HKEY_LOCAL_MACHINE,
        r'SOFTWARE\Wow6432Node\CoreTechSystem\MDX_ParallelComputing')
    valueInfo = _winreg.QueryInfoKey(
        pyHKEY)  # Read the value infomation(name & data) under the subKey
    versionPathList = []
    for i in range(0, valueInfo[1], 1):
        value = _winreg.EnumValue(pyHKEY, i)
        if "_INSTALLDIR" in value[0]:
            versionPathList.append(value[1])
    if versionPathList == []:
        return ("MDX setting address Error !!")
    else:
        versionParentPath = str(versionPathList[-1])

    # Read the DailyBuild version
    with open(r"{}\Moldex3D.ver".format(versionParentPath), "r") as localfile:
        versionLine = localfile.read()
    patten = r"R[0-9]{2}[A-Za-z0-9]+ 64-bit \(Build[0-9]{4}[.][0-9]{4}"
    version = re.search(patten, versionLine).group().replace(" 64-bit (", "")
    _winreg.CloseKey(pyHKEY)
    return (version)