Example #1
0
File: detect.py Project: uael/conan
def _visual_compiler(output, version):
    'version have to be 8.0, or 9.0 or... anything .0'
    from six.moves import winreg

    try:
        hKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                              r"SOFTWARE\Microsoft\Windows\CurrentVersion")
        winreg.QueryValueEx(hKey, "ProgramFilesDir (x86)")
        is_64bits = True
    except EnvironmentError:
        is_64bits = False
    finally:
        winreg.CloseKey(hKey)

    if is_64bits:
        key_name = r'SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VC7'
    else:
        key_name = r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VC7'

    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name)
        winreg.QueryValueEx(key, version)
        installed_version = Version(version).major(fill=False)
        compiler = "Visual Studio"
        output.success("Found %s %s" % (compiler, installed_version))
        return compiler, installed_version
    except EnvironmentError:
        return None
Example #2
0
def get_latest_nastran_directory():
    def enum_keys(handle):
        for i in range(2**10):
            try:
                yield winreg.EnumKey(handle, i)
            except WindowsError as e:
                if e.winerror != 259:
                    raise
                return

    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                        "SOFTWARE\\MSC.Software Corporation", winreg.KEY_READ
                        | winreg.KEY_WOW64_32KEY) as software_msc:
        nastrans = sorted([
            name for name in enum_keys(software_msc) if "MSC Nastran" in name
            and "MSC Nastran Documentation" not in name
        ])
        if not nastrans:
            exitwitherror(
                "Nastran.py: Can't read NASTRAN path from registry. Do you have it installed?",
                -1)
        latest_nastran = nastrans[-1]
        with winreg.OpenKey(software_msc,
                            latest_nastran + "\\Latest") as latest_key:
            version = six.text_type(winreg.QueryValueEx(latest_key, None)[0])
        with winreg.OpenKey(software_msc,
                            "{}\\{}".format(latest_nastran,
                                            version)) as nastran_key:
            return six.text_type(winreg.QueryValueEx(nastran_key, "Path")[0])
Example #3
0
    def _get_vix_path():
        """Finds the expected install path for the so/dll.

        :returns: Expected path.
        :rtype: str

        :raises NotImplemented: If the OS/architecture are not recognized.
        """

        os_name = platform.system()

        if os_name == 'Linux':
            return '/usr/lib/libvixAllProducts.so'

        elif os_name == 'Darwin':
            return '/Applications/VMware Fusion.app/Contents/Public/libvixAllProducts.dylib'

        elif os_name == 'Windows':
            arch = platform.architecture()[0].lower()
            machine = platform.machine().lower()

            # Py: 32; Machine: 32: %ProgramFiles%\VMware\VMware VIX\VixAllProductsDyn.dll
            # Py: 32; Machine: 64: %ProgramFiles(x86)%\VMware\VMware VIX\VixAllProductsDyn.dll
            # Py: 64; Machine: 32: N/A
            # Py: 64; Machine: 64: %ProgramFiles(x86)%\VMware\VMware VIX\Vix64AllProductsDyn.dll

            from six.moves import winreg

            try:
                if machine == 'amd64':
                    base_path = winreg.QueryValueEx(
                        winreg.OpenKey(
                            winreg.HKEY_LOCAL_MACHINE,
                            r'SOFTWARE\WOW6432Node\VMware, Inc.\VMware VIX'),
                        'InstallPath')[0]
                else:
                    base_path = winreg.QueryValueEx(
                        winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                                       r'SOFTWARE\VMware, Inc.\VMware VIX'),
                        'InstallPath')[0]
            except OSError:
                base_path = os.getenv(
                    'ProgramFiles(x86)') if machine == 'amd64' else os.getenv(
                        'ProgramFiles')
                base_path = os.path.join(base_path, 'VMware', 'VMware VIX')

            base_path = os.path.join(
                base_path, 'Vix64AllProductsDyn.dll'
                if arch == '64bit' else 'VixAllProductsDyn.dll')

            return base_path

        raise NotImplementedError(
            'Unrecognized OS or architecture ({0}, {1}, {2})'.format(
                platform.architecture(), platform.machine(),
                platform.system()))
Example #4
0
def create_usage(ifs):
    """
    Return usage string.

    :type ifs: list[str]
    :param ifs: List of network interfaces to include in help text.

    :rtype : str
    :return: Usage text.
    """
    message = """USAGE: network_monitor.py
    [-d|--device DEVICE #]    device to sniff on (see list below)
    [-f|--filter PCAP FILTER] BPF filter string
    [-P|--log_path PATH]      log directory to store pcaps to
    [-l|--log_level LEVEL]    log level: default 1, increase for more verbosity
    [--port PORT]             TCP port to bind this agent to

Network Device List:
"""
    for index, pcapy_device in enumerate(ifs):
        # if we are on windows, try and resolve the device UUID into an IP address.
        if sys.platform.startswith("win"):
            from six.moves import winreg  # pytype: disable=import-error

            try:
                # extract the device UUID and open the TCP/IP parameters key for it.
                pcapy_device = pcapy_device[
                    pcapy_device.index("{"):pcapy_device.index("}") + 1]
                subkey = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\%s" % pcapy_device
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey)

                # if there is a DHCP address snag that, otherwise fall back to the IP address.
                try:
                    ip = winreg.QueryValueEx(key, "DhcpIPAddress")[0]
                except Exception:
                    ip = winreg.QueryValueEx(key, "IPAddress")[0][0]

                pcapy_device = pcapy_device + "\t" + ip
            except Exception:
                pass
        elif sys.platform.startswith("lin"):
            try:
                ip = ni.ifaddresses(pcapy_device)[ni.AF_INET][0]["addr"]
                pcapy_device = pcapy_device + "\t" + ip
            except Exception:
                pass

        message += "    [%d] %s\n" % (index, pcapy_device)
    return message
Example #5
0
    def __init__( self, vmx, user='', password='', vmrun='', debug=False ):

        self.VM_FILE    =   vmx         # TODO strict censor?
        self.VM_ADMIN   =   user
        self.VM_PASS    =   password
        self.DEBUG      =   debug

        if vmrun != '':
            self.VMRUN_PATH = vmrun
        else:
            if os.sys.platform == 'darwin':
                self.provider = 'fusion'
                self.VMRUN_PATH = '/Applications/VMware\ Fusion.app/Contents/Library/vmrun'
            elif os.sys.platform == "win32":
                # get vmrun.exe's full path via registry
                from six.moves import winreg as _winreg
                reg = _winreg.ConnectRegistry( None, _winreg.HKEY_LOCAL_MACHINE )
                try:
                    # Known registry key location in Windows 10
                    rh = _winreg.OpenKey( reg, r'SOFTWARE\WOW6432Node\VMware, Inc.\VMware Workstation' )
                    try:
                        vw_dir = _winreg.QueryValueEx( rh, 'InstallPath' )[0]
                    finally:
                        _winreg.CloseKey( rh )
                except WindowsError:
                    # Previously used registry key location
                    rh = _winreg.OpenKey( reg, r'SOFTWARE\VMware, Inc.\VMware Workstation' )
                    try:
                        vw_dir = _winreg.QueryValueEx( rh, 'InstallPath' )[0]
                    finally:
                        _winreg.CloseKey( rh )
                finally:
                    reg.Close()

                self.provider = 'ws'
                if vw_dir != '':
                    self.VMRUN_PATH = vw_dir + 'vmrun.exe'
            else:
                self.provider = 'ws'
                if os.environ.has_key("PATH"):
                    for path in os.environ["PATH"].split(os.pathsep):
                        tmp_file = path + os.sep + "vmrun"
                        if os.path.exists(tmp_file):
                            self.VMRUN_PATH = tmp_file
                            break
        
        vmrun_path = getattr(self, 'VMRUN_PATH', None)
        if vmrun_path is None:
            raise RuntimeError('Could not locate vmrun executable!')
    def check_fips_mode_os():
        """ Function to check for the OS fips mode

        :param key: string to encrypt with
        :type key: str.

        :returns: returns True if FIPS mode is active, False otherwise
        """
        fips = False
        if os.name == 'nt':
            reg = winreg.ConnectRegistry(None, HKEY_LOCAL_MACHINE)
            try:
                reg = winreg.OpenKey(reg, 'System\\CurrentControlSet\\Control\\'\
                                            'Lsa\\FipsAlgorithmPolicy')
                winreg.QueryInfoKey(reg)
                value, _ = winreg.QueryValueEx(reg, 'Enabled')
                if value:
                    fips = True
            except:
                fips = False
        else:
            try:
                fipsfile = open("/proc/sys/crypto/fips_enabled")
                result = fipsfile.readline()
                if int(result) > 0:
                    fipsfile = True
                fipsfile.close()
            except:
                fips = False
        return fips
Example #7
0
    def _get_counter_dictionary(self):
        if WinPDHCounter.pdh_counter_dict:
            # already populated
            return
        if WinPDHCounter._use_en_counter_names:
            # already found out the registry isn't there
            return

        try:
            val, t = winreg.QueryValueEx(winreg.HKEY_PERFORMANCE_DATA, "Counter 009")
        except:  # noqa: E722, B001
            self.logger.error("Windows error; performance counters not found in registry")
            self.logger.error("Performance counters may need to be rebuilt.")
            raise

        # val is an array of strings.  The underlying win32 API returns a list of strings
        # which is the counter name, counter index, counter name, counter index (in windows,
        # a multi-string value)
        #
        # the python implementation translates the multi-string value into an array of strings.
        # the array of strings then becomes
        # array[0] = counter_index_1
        # array[1] = counter_name_1
        # array[2] = counter_index_2
        # array[3] = counter_name_2
        #
        # see https://support.microsoft.com/en-us/help/287159/using-pdh-apis-correctly-in-a-localized-language
        # for more detail

        # create a table of the keys to the counter index, because we want to look up
        # by counter name. Some systems may have an odd number of entries, don't
        # accidentally index at val[len(val]
        for idx in range(0, len(val) - 1, 2):
            WinPDHCounter.pdh_counter_dict[val[idx + 1]].append(val[idx])
Example #8
0
def find_windows_10_sdk():
    """finds valid Windows 10 SDK version which can be passed to vcvarsall.bat (vcvars_command)"""
    # uses the same method as VCVarsQueryRegistry.bat
    from six.moves import winreg  # @UnresolvedImport
    hives = [
        (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Wow6432Node'),
        (winreg.HKEY_CURRENT_USER, r'SOFTWARE\Wow6432Node'),
        (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE'),
        (winreg.HKEY_CURRENT_USER, r'SOFTWARE')
    ]
    for key, subkey in hives:
        try:
            hkey = winreg.OpenKey(key, r'%s\Microsoft\Microsoft SDKs\Windows\v10.0' % subkey)
            installation_folder, _ = winreg.QueryValueEx(hkey, 'InstallationFolder')
            if os.path.isdir(installation_folder):
                include_dir = os.path.join(installation_folder, 'include')
                for sdk_version in os.listdir(include_dir):
                    if os.path.isdir(os.path.join(include_dir, sdk_version)) and sdk_version.startswith('10.'):
                        windows_h = os.path.join(include_dir, sdk_version, 'um', 'Windows.h')
                        if os.path.isfile(windows_h):
                            return sdk_version
        except EnvironmentError:
            pass
        finally:
            winreg.CloseKey(hkey)
    return None
Example #9
0
def win32FontDirectory():
    """
    Return the user-specified font directory for Win32.  This is
    looked up from the registry key::

      \\\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\Fonts

    If the key is not found, $WINDIR/Fonts will be returned.
    """
    try:
        from six.moves import winreg
    except ImportError:
        pass  # Fall through to default
    else:
        try:
            user = winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders)
            try:
                try:
                    return winreg.QueryValueEx(user, 'Fonts')[0]
                except OSError:
                    pass  # Fall through to default
            finally:
                winreg.CloseKey(user)
        except OSError:
            pass  # Fall through to default
    return os.path.join(os.environ['WINDIR'], 'Fonts')
Example #10
0
    def lookup(self, key, name):
        """
        Look for values in registry in Microsoft software registry.

        Parameters
        ----------
        key: str
            Registry key path where look.
        name: str
            Value name to find.

        Return
        ------
        str: value
        """
        KEY_READ = winreg.KEY_READ
        openkey = winreg.OpenKey
        ms = self.microsoft
        for hkey in self.HKEYS:
            try:
                bkey = openkey(hkey, ms(key), 0, KEY_READ)
            except (OSError, IOError):
                if not self.pi.current_is_x86():
                    try:
                        bkey = openkey(hkey, ms(key, True), 0, KEY_READ)
                    except (OSError, IOError):
                        continue
                else:
                    continue
            try:
                return winreg.QueryValueEx(bkey, name)[0]
            except (OSError, IOError):
                pass
Example #11
0
 def get(class_, name, default=NoDefault):
     try:
         value, type = winreg.QueryValueEx(class_.key, name)
         return value
     except WindowsError:
         if default is not class_.NoDefault:
             return default
         raise ValueError("No such key", name)
Example #12
0
    def get_config_value(self, name, section=None):
        key_name = self._get_config_key_name(section)

        try:
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name) as key:
                (value, regtype) = winreg.QueryValueEx(key, name)
                return value
        except WindowsError:
            return None
Example #13
0
 def get_user_home(self, username):
     user_sid = self.get_user_sid(username)
     if user_sid:
         with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\'
                             'Microsoft\\Windows NT\\CurrentVersion\\'
                             'ProfileList\\%s' % user_sid) as key:
             return winreg.QueryValueEx(key, 'ProfileImagePath')[0]
     LOG.debug('Home directory not found for user %r', username)
     return None
Example #14
0
 def get_browser_path():
     '''获取chorme.exe的路径
     '''
     from six.moves import winreg
     sub_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome"
     try:
         hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key)
         install_dir, _ = winreg.QueryValueEx(hkey, "InstallLocation")
         winreg.CloseKey(hkey)
     except WindowsError:
         try:
             hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key)
             install_dir, _ = winreg.QueryValueEx(hkey, "InstallLocation")
         except WindowsError:
             sub_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"
             hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key)
             install_dir, _ = winreg.QueryValueEx(hkey, "Path")
     return install_dir + "\\chrome.exe"
Example #15
0
 def GetEnv(name):
     root = winreg.HKEY_CURRENT_USER
     subkey = 'Environment'
     key = winreg.OpenKey(root, subkey, 0, winreg.KEY_READ)
     try:
         value, _ = winreg.QueryValueEx(key, name)
     # pylint:disable=undefined-variable, This variable is defined in windows.
     except WindowsError:
         return ''
     return value
Example #16
0
 def get_san_policy(self):
     with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                         'SYSTEM\\CurrentControlSet\\Services\\partmgr\\'
                         'Parameters') as key:
         try:
             san_policy = winreg.QueryValueEx(key, 'SanPolicy')[0]
         except WindowsError as ex:
             if ex.winerror != 2:
                 raise
             san_policy = base.SAN_POLICY_OFFLINE_SHARED
         return san_policy
Example #17
0
 def get_browser_path():
     '''获取chorme.exe的路径
     '''
     from six.moves import winreg
     sub_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Chrome"
     install_dir = ''
     try:
         hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key)
         install_dir, _ = winreg.QueryValueEx(hkey, "InstallLocation")
         winreg.CloseKey(hkey)
     except WindowsError:
         try:
             hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key)
             install_dir, _ = winreg.QueryValueEx(hkey, "InstallLocation")
         except WindowsError:
             try:
                 sub_key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"
                 hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key)
                 install_dir, _ = winreg.QueryValueEx(hkey, "Path")
             except WindowsError:
                 for env_dir in os.getenv('PATH').split(';'):
                     if os.path.exists(os.path.join(env_dir, 'chrome.exe')):
                         install_dir = env_dir
                         break
                 if not install_dir:
                     app_dirs = [
                         os.getenv('LOCALAPPDATA'),
                         os.getenv('ProgramFiles(x86)'),
                         os.getenv('ProgramW6432')
                     ]
                     for app_dir in app_dirs:
                         if (os.path.exists(
                                 os.path.join(app_dir,
                                              r'Google\Chrome\Application',
                                              'chrome.exe'))):
                             install_dir = os.path.join(
                                 app_dir, r'Google\Chrome\Application')
                             break
     if not install_dir:
         raise WindowsError('未找到Chrome可执行文件路径')
     return os.path.join(install_dir, "chrome.exe")
Example #18
0
def _visual_compiler(output, version):
    'version have to be 8.0, or 9.0 or... anything .0'
    if platform.system().startswith("CYGWIN"):
        return _visual_compiler_cygwin(output, version)

    if version == "15":
        vs_path = os.getenv('vs150comntools')
        path = vs_path or vs_installation_path("15")
        if path:
            compiler = "Visual Studio"
            output.success("Found %s %s" % (compiler, "15"))
            return compiler, "15"
        return None

    version = "%s.0" % version
    from six.moves import winreg  # @UnresolvedImport
    try:
        hKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                              r"SOFTWARE\Microsoft\Windows\CurrentVersion")
        winreg.QueryValueEx(hKey, "ProgramFilesDir (x86)")
        is_64bits = True
    except EnvironmentError:
        is_64bits = False
    finally:
        winreg.CloseKey(hKey)

    if is_64bits:
        key_name = r'SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VC7'
    else:
        key_name = r'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VC7'

    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name)
        winreg.QueryValueEx(key, version)

        installed_version = Version(version).major(fill=False)
        compiler = "Visual Studio"
        output.success("Found %s %s" % (compiler, installed_version))
        return compiler, installed_version
    except EnvironmentError:
        return None
Example #19
0
 def get_uac_remote_restrictions(self):
     try:
         with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                             self._SYSTEM_POLICIES_KEY) as key:
             (value, regtype) = winreg.QueryValueEx(key,
                                                    self._LATFP_VALUE_NAME)
             return not bool(value)
     except WindowsError as e:
         if e.errno == 0x2:
             return True
         else:
             raise
Example #20
0
 def _check_server_level(self, server_level):
     try:
         with winreg.OpenKey(
                 winreg.HKEY_LOCAL_MACHINE,
                 "Software\\Microsoft\\Windows NT\\CurrentVersion\\Server\\"
                 "ServerLevels") as key:
             return winreg.QueryValueEx(key, server_level)[0] == 1
     except WindowsError as ex:
         if ex.winerror == 2:
             return False
         else:
             raise
Example #21
0
def _system_registry_key(key, subkey, query):
    from six.moves import winreg  # @UnresolvedImport
    try:
        hkey = winreg.OpenKey(key, subkey)
    except (OSError, WindowsError):  # Raised by OpenKey/Ex if the function fails (py3, py2)
        return None
    else:
        try:
            value, _ = winreg.QueryValueEx(hkey, query)
            return value
        except EnvironmentError:
            return None
        finally:
            winreg.CloseKey(hkey)
Example #22
0
def _get_registry_dhcp_server(adapter_name):
    with winreg.OpenKey(
            winreg.HKEY_LOCAL_MACHINE,
            "SYSTEM\\CurrentControlSet\\Services\\" +
            "Tcpip\\Parameters\\Interfaces\\%s" % adapter_name, 0,
            winreg.KEY_READ) as key:
        try:
            dhcp_server = winreg.QueryValueEx(key, "DhcpServer")[0]
            if dhcp_server == "255.255.255.255":
                dhcp_server = None
            return dhcp_server
        except Exception as ex:
            # Not found
            if ex.errno != 2:
                raise
Example #23
0
 def get_password(self, service, username):
     """Get password of the username for the service
     """
     try:
         # fetch the password
         key = self._key_for_service(service)
         hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key)
         password_saved = winreg.QueryValueEx(hkey, username)[0]
         password_base64 = password_saved.encode('ascii')
         # decode with base64
         password_encrypted = base64.decodestring(password_base64)
         # decrypted the password
         password = _win_crypto.decrypt(password_encrypted).decode('utf-8')
     except EnvironmentError:
         password = None
     return password
Example #24
0
def _check_long_paths_support():
    if platform.system() != "Windows":
        return True
    if sys.version_info < (3, 6):
        return False
    from six.moves import winreg
    try:
        hKey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                              r"SYSTEM\CurrentControlSet\Control\FileSystem")
        result = winreg.QueryValueEx(hKey, "LongPathsEnabled")
        key_value = result[0]
        return key_value == 1
    except EnvironmentError:
        return False
    finally:
        winreg.CloseKey(hKey)
    return False
Example #25
0
    def __init__(self, dll_location=None):
        """
        Initializes the raildriver.dll interface.

        :param dll_location Optionally pass the location of raildriver.dll if in some custom location.
                            If not passed will try to guess the location by using the Windows Registry.
        """
        if not dll_location:
            steam_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\Valve\\Steam')
            steam_path = winreg.QueryValueEx(steam_key, 'SteamPath')[0]
            railworks_path = os.path.join(steam_path, 'steamApps', 'common', 'railworks', 'plugins')
            dll_location = os.path.join(railworks_path, 'raildriver.dll')
            if not os.path.isfile(dll_location):
                raise EnvironmentError('Unable to automatically locate raildriver.dll.')
        self.dll = ctypes.cdll.LoadLibrary(dll_location)
        for function_name, restype in self._restypes.items():
            getattr(self.dll, function_name).restype = restype
Example #26
0
    def _update_registry():
        # From MSDN documentation:
        #
        # The hook procedure should process a message in less time than the
        # data entry specified in the LowLevelHooksTimeout value in the
        # following registry key:
        #
        # HKEY_CURRENT_USER\Control Panel\Desktop
        #
        # The value is in milliseconds. If the hook procedure times out, the
        # system passes the message to the next hook. However, on Windows 7 and
        # later, the hook is silently removed without being called. There is no
        # way for the application to know whether the hook is removed.

        def _open_key(rights):
            return winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                  r'Control Panel\Desktop', 0, rights)

        REG_LLHOOK_KEY_FULL_NAME = r'HKEY_CURRENT_USER\Control Panel\Desktop\LowLevelHooksTimeout'
        REG_LLHOOK_KEY_VALUE_NAME = 'LowLevelHooksTimeout'
        REG_LLHOOK_KEY_VALUE_TYPE = winreg.REG_DWORD
        REG_LLHOOK_KEY_VALUE = 5000

        read_key = _open_key(winreg.KEY_READ)
        try:
            value, value_type = winreg.QueryValueEx(read_key,
                                                    REG_LLHOOK_KEY_VALUE_NAME)
        except WindowsError:
            value, value_type = (None, None)

        if value_type != REG_LLHOOK_KEY_VALUE_TYPE or value != REG_LLHOOK_KEY_VALUE:
            try:
                write_key = _open_key(winreg.KEY_WRITE)
                winreg.SetValueEx(write_key, REG_LLHOOK_KEY_VALUE_NAME, 0,
                                  REG_LLHOOK_KEY_VALUE_TYPE,
                                  REG_LLHOOK_KEY_VALUE)
            except WindowsError:
                log.warning(
                    'could not update registry key: %s, see documentation',
                    REG_LLHOOK_KEY_FULL_NAME)
            else:
                log.warning(
                    'the following registry key has been updated, '
                    'you should reboot: %s', REG_LLHOOK_KEY_FULL_NAME)
Example #27
0
    def _get_local_auth(self):
        username = password = ""
        if platform.system() in ('Windows', 'Microsoft'):
            app_data_path = os.environ.get("APPDATA")
            if not app_data_path:
                from six.moves import winreg
                hkey = winreg.OpenKey(
                    winreg.HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders",
                )
                app_data_reg = winreg.QueryValueEx(hkey, "AppData")
                app_data_path = app_data_reg[0]
                winreg.CloseKey(hkey)

            auth_file = os.path.join(app_data_path, "deluge", "auth")
        else:
            from xdg.BaseDirectory import save_config_path
            try:
                auth_file = os.path.join(save_config_path("deluge"), "auth")
            except OSError:
                return username, password

        if os.path.exists(auth_file):
            for line in open(auth_file):
                if line.startswith("#"):
                    # This is a comment line
                    continue
                line = line.strip()
                try:
                    lsplit = line.split(":")
                except Exception:
                    continue

                if len(lsplit) == 2:
                    username, password = lsplit
                elif len(lsplit) == 3:
                    username, password, level = lsplit
                else:
                    continue

                if username == "localclient":
                    return username, password

        return "", ""
Example #28
0
 def wait_for_boot_completion(self):
     try:
         with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                             "SYSTEM\\Setup\\Status\\SysprepStatus", 0,
                             winreg.KEY_READ) as key:
             while True:
                 gen_state = winreg.QueryValueEx(key,
                                                 "GeneralizationState")[0]
                 if gen_state == 7:
                     break
                 time.sleep(1)
                 LOG.info('Waiting for sysprep completion. '
                          'GeneralizationState: %d' % gen_state)
     except WindowsError as ex:
         if ex.winerror == 2:
             LOG.debug('Sysprep data not found in the registry, '
                       'skipping sysprep completion check.')
         else:
             raise ex
Example #29
0
    def get_iscsi_initiator(self):
        """Get iscsi initiator name for this machine."""

        computer_system = self._conn_cimv2.Win32_ComputerSystem()[0]
        hostname = computer_system.name
        keypath = ("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\"
                   "iSCSI\\Discovery")
        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, keypath, 0,
                                 winreg.KEY_ALL_ACCESS)
            temp = winreg.QueryValueEx(key, 'DefaultInitiatorName')
            initiator_name = str(temp[0])
            winreg.CloseKey(key)
        except Exception:
            LOG.info(
                _LI("The ISCSI initiator name can't be found. "
                    "Choosing the default one"))
            initiator_name = "iqn.1991-05.com.microsoft:" + hostname.lower()
            if computer_system.PartofDomain:
                initiator_name += '.' + computer_system.Domain.lower()
        return initiator_name
Example #30
0
 def wait_for_boot_completion(self):
     try:
         with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                             "SYSTEM\\Setup\\Status\\SysprepStatus", 0,
                             winreg.KEY_READ) as key:
             while True:
                 gen_state = winreg.QueryValueEx(key,
                                                 "GeneralizationState")[0]
                 if gen_state == 7:
                     break
                 # Bigstep -> not executing service during sysprep
                 LOG.info('Stopping service, as sysprep is running')
                 self.terminate()
                 # time.sleep(1)
                 # LOG.info('Waiting for sysprep completion. '
                 #         'GeneralizationState: %d', gen_state)
     except WindowsError as ex:
         if ex.winerror == 2:
             LOG.debug('Sysprep data not found in the registry, '
                       'skipping sysprep completion check.')
         else:
             raise ex