Exemple #1
0
    def __init__(self):
        self.path = "WindowsRegistry"
        self.map = {}
        try:
            import win32api


##            import win32con
        except ImportError:
            pass
        else:
            HKEY_CURRENT_USER = -2147483647
            HKEY_LOCAL_MACHINE = -2147483646
            KEY_ALL_ACCESS = 983103
            KEY_READ = 131097
            subkey = r"Software\Python\PythonCore\%s\Modules" % sys.winver
            for root in (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE):
                try:
                    #hkey = win32api.RegOpenKeyEx(root, subkey, 0, KEY_ALL_ACCESS)
                    hkey = win32api.RegOpenKeyEx(root, subkey, 0, KEY_READ)
                except:
                    pass
                else:
                    numsubkeys, numvalues, lastmodified = win32api.RegQueryInfoKey(
                        hkey)
                    for i in range(numsubkeys):
                        subkeyname = win32api.RegEnumKey(hkey, i)
                        #hskey = win32api.RegOpenKeyEx(hkey, subkeyname, 0, KEY_ALL_ACCESS)
                        hskey = win32api.RegOpenKeyEx(hkey, subkeyname, 0,
                                                      KEY_READ)
                        val = win32api.RegQueryValueEx(hskey, '')
                        desc = getDescr(val[0])
                        self.map[subkeyname] = (val[0], desc)
                        hskey.Close()
                    hkey.Close()
                    break
Exemple #2
0
def _GetServiceShortName(longName):
    # looks up a services name
    # from the display name
    # Thanks to Andy McKay for this code.
    access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
    hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                               "SYSTEM\\CurrentControlSet\\Services", 0,
                               access)
    num = win32api.RegQueryInfoKey(hkey)[0]
    longName = longName.lower()
    # loop through number of subkeys
    for x in range(0, num):
        # find service name, open subkey
        svc = win32api.RegEnumKey(hkey, x)
        skey = win32api.RegOpenKey(hkey, svc, 0, access)
        try:
            # find display name
            thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
            if thisName.lower() == longName:
                return svc
        except win32api.error:
            # in case there is no key called DisplayName
            pass
    return None
def set_wallpaper(picpath):
    if sys.platform == 'win32':
        import win32api, win32con, win32gui
        k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,
                                'Control Panel\Desktop', 0,
                                win32con.KEY_ALL_ACCESS)
        curpath = win32api.RegQueryValueEx(k, 'Wallpaper')[0]
        if curpath == picpath:
            pass
        else:
            # win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2")#2 for tile,0 for center
            # win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
            win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,
                                          picpath, 1 + 2)
        win32api.RegCloseKey(k)
    else:
        curpath = commands.getstatusoutput(
            'gsettings get org.gnome.desktop.background picture-uri')[1][1:-1]
        if curpath == picpath:
            pass
        else:
            commands.getstatusoutput(
                'DISPLAY=:0 gsettings set org.gnome.desktop.background picture-uri "%s"'
                % (picpath))
Exemple #4
0
def __FindSvcDeps(findName):
    if type(findName) is pywintypes.UnicodeType: findName = str(findName)
    dict = {}
    k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                            "SYSTEM\\CurrentControlSet\\Services")
    num = 0
    while 1:
        try:
            svc = win32api.RegEnumKey(k, num)
        except win32api.error:
            break
        num = num + 1
        sk = win32api.RegOpenKey(k, svc)
        try:
            deps, typ = win32api.RegQueryValueEx(sk, "DependOnService")
        except win32api.error:
            deps = ()
        for dep in deps:
            dep = dep.lower()
            dep_on = dict.get(dep, [])
            dep_on.append(svc)
            dict[dep] = dep_on

    return __ResolveDeps(findName, dict)
Exemple #5
0
def get_reg_values(reg_key, value_list):
    # open the reg key
    try:
        reg_key = win32api.RegOpenKeyEx(*reg_key)
    except pywintypes.error as e:
        raise Exception("Failed to open registry key!")
    # Get the values
    try:
        values = [(win32api.RegQueryValueEx(reg_key, name), data_type) for name, data_type in value_list]
        # values list of ((value, type), expected_type)
        for (value, data_type), expected in values:
            if data_type != expected:
                raise Exception("Bad registry value type! Expected %d, got %d instead." % (expected, data_type))
        # values okay, leave only values
        values = [value for ((value, data_type), expected) in values]
    except pywintypes.error as e:
        raise Exception("Failed to get registry value!")
    finally:
        try:
            win32api.RegCloseKey(reg_key)
        except pywintypes.error as e:
            # We don't care if reg key close failed...
            pass
    return tuple(values)
Exemple #6
0
def GetCurrentDir(bUnicode):
    if sys.platform.startswith("win") and hasattr(sys, "frozen"):
        # get current dir where the file was executed form
        if sys.frozen == "dll":
            this_filename = win32api.GetModuleFileName(sys.frozendllhandle)
        else:
            this_filename = sys.executable
        currentDir = os.path.split(this_filename)[0]

        # attempt to read the config from the working folder
        conf = Config.Settings(os.path.join(currentDir, 'ClamWin.conf'))

        # not a standalone version
        if not conf.Read() or conf.Get('UI', 'Standalone') != '1':
            try:
                # try HKCU first and then HKLM keys
                # (this is to enable non admin user to install and use clamwin)
                try:
                    key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,
                                                'Software\\ClamWin')
                except win32api.error:
                    key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
                                                'Software\\ClamWin')
                currentDir = SafeExpandEnvironmentStrings(
                    win32api.RegQueryValueEx(key, 'Path')[0])
            except win32api.error:
                pass
    else:
        try:
            currentDir = os.path.split(os.path.abspath(__file__))[0]
        except NameError:  # No __file__ attribute (in boa debugger)
            currentDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
    if bUnicode and sys.platform.startswith("win"):
        # change encoding to proper unicode
        currentDir = pywintypes.Unicode(currentDir)
    return currentDir
Exemple #7
0
def FindHelpPath(helpFile, helpDesc, searchPaths):
    # See if the current registry entry is OK
    import os, win32api, win32con
    try:
        key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0,
                                  win32con.KEY_ALL_ACCESS)
        try:
            try:
                path = win32api.RegQueryValueEx(key, helpDesc)[0]
                if FileExists(os.path.join(path, helpFile)):
                    return os.path.abspath(path)
            except win32api.error:
                pass  # no registry entry.
        finally:
            key.Close()
    except win32api.error:
        pass
    for pathLook in searchPaths:
        if FileExists(os.path.join(pathLook, helpFile)):
            return os.path.abspath(pathLook)
        pathLook = os.path.join(pathLook, "Help")
        if FileExists(os.path.join(pathLook, helpFile)):
            return os.path.abspath(pathLook)
    raise error("The help file %s can not be located" % helpFile)
Exemple #8
0
    def testValues(self):
        key_name = r'PythonTestHarness\win32api'
        ## tuples containing value name, value type, data
        values=(
            (None, win32con.REG_SZ, 'This is default unnamed value'),
            ('REG_SZ', win32con.REG_SZ,'REG_SZ text data'),
            ('REG_EXPAND_SZ', win32con.REG_EXPAND_SZ, '%systemdir%'),
            ## REG_MULTI_SZ value needs to be a list since strings are returned as a list
            ('REG_MULTI_SZ', win32con.REG_MULTI_SZ, ['string 1','string 2','string 3','string 4']),
            ('REG_MULTI_SZ_empty', win32con.REG_MULTI_SZ, []),
            ('REG_DWORD', win32con.REG_DWORD, 666),
            ('REG_QWORD_INT', win32con.REG_QWORD, 99),
            ('REG_QWORD', win32con.REG_QWORD, 2**33),
            ('REG_BINARY', win32con.REG_BINARY, str2bytes('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x01\x00')),
            )

        hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, key_name)
        for value_name, reg_type, data in values:
            win32api.RegSetValueEx(hkey, value_name, None, reg_type, data)

        for value_name, orig_type, orig_data in values:
            data, typ=win32api.RegQueryValueEx(hkey, value_name)
            self.assertEqual(typ, orig_type)
            self.assertEqual(data, orig_data)
Exemple #9
0
def read_value(hive, key, vname=None, use_32bit_registry=False):
    r'''
    Reads a registry value entry or the default value for a key.

    :param str hive: The name of the hive. Can be one of the following

        - HKEY_LOCAL_MACHINE or HKLM
        - HKEY_CURRENT_USER or HKCU
        - HKEY_USER or HKU

    :param str key: The key (looks like a path) to the value name.

    :param str vname: The value name. These are the individual name/data pairs
       under the key. If not passed, the key (Default) value will be returned

    :param bool use_32bit_registry: Accesses the 32bit portion of the registry
       on 64bit installations. On 32bit machines this is ignored.

    :return: A dictionary containing the passed settings as well as the
       value_data if successful. If unsuccessful, sets success to False.

    :rtype: dict

    If vname is not passed:

    - Returns the first unnamed value (Default) as a string.
    - Returns none if first unnamed value is empty.
    - Returns False if key not found.

    CLI Example:

    .. code-block:: bash

        salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
    '''
    # If no name is passed, the default value of the key will be returned
    # The value name is Default

    # Setup the return array
    local_hive = _to_unicode(hive)
    local_key = _to_unicode(key)
    local_vname = _to_unicode(vname)

    ret = {'hive':  local_hive,
           'key':   local_key,
           'vname': local_vname,
           'vdata': None,
           'success': True}

    if not vname:
        ret['vname'] = '(Default)'

    registry = Registry()
    hkey = registry.hkeys[local_hive]
    access_mask = registry.registry_32[use_32bit_registry]

    try:
        handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
        try:
            # RegQueryValueEx returns and accepts unicode data
            vdata, vtype = win32api.RegQueryValueEx(handle, local_vname)
            if vdata or vdata in [0, '']:
                ret['vtype'] = registry.vtype_reverse[vtype]
                if vtype == 7:
                    ret['vdata'] = [_to_mbcs(i) for i in vdata]
                else:
                    ret['vdata'] = _to_mbcs(vdata)
            else:
                ret['comment'] = 'Empty Value'
        except WindowsError:  # pylint: disable=E0602
            ret['vdata'] = ('(value not set)')
            ret['vtype'] = 'REG_SZ'
    except pywintypes.error as exc:  # pylint: disable=E0602
        log.debug(exc)
        log.debug('Cannot find key: {0}\\{1}'.format(local_hive, local_key))
        ret['comment'] = 'Cannot find key: {0}\\{1}'.format(local_hive, local_key)
        ret['success'] = False
    return ret
Exemple #10
0
        win32api.RegQueryInfoKey(key)  # RegQueryInfoKey函数查询项的基本信息; 返回项的子项数目、项值数目,以及最后一次修改时间

      如:
        import win32api
        import win32con

        # 打开“HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer”项
        key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,'SOFTWARE\\Microsoft\\Internet Explorer',0, win32con.KEY_ALL_ACCESS)

        # 读取项的默认值''
        # 输出为空,表示其默认值未设置
        print win32api.RegQueryValue(key,'')

        #读取项值名称为Version的项值数据,也就是Internet Explorer的版本
        print win32api.RegQueryValueEx(key,'Version') # 显示如:('6.0.2900.2180', 1)
        print win32api.RegQueryInfoKey(key)  # 查询项的基本信息,显示如:(26, 7, 128178812229687500L)

    6.  设置项值
        win32api.RegSetValue(key,subKey,type,value) # 设置项的默认值
            Key:已经打开的项的句柄。
            subKey:所要设置的子项。
            Type:项值的类型,必须为 win32con.REG_SZ。
            Value:项值数据,为字符串。

        win32api.RegSetValueEx(key,valueName,reserved,type,value) # 要修改或重新设置注册表某一项的项值。如果项值存在,则修改该项值,如果不存在,则添加该项值。
            Key:要设置的项的句柄。
            valueName:要设置的项值名称。
            Reserved:保留,可以设为0。
            Type:项值的类型。
            Value:所要设置的值。
Exemple #11
0
DOT_EXE = 'dot'
bin_search_path = []

if os.name == 'nt':
    DOT_EXE = 'dot.exe'

    # patch from Joachim Bauch [email protected]
    # on Windows, the path to the ATT Graphviz installation
    # is read from the registry.
    try:
        import win32api, win32con
        # make sure that "key" is defined in our except block
        key = None
        try:
            key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, r'SOFTWARE\ATT\Graphviz')
            value, type = win32api.RegQueryValueEx(key, 'InstallPath')
            bin_search_path = [os.path.join(str(value), 'bin')]
        except:
            if key: win32api.RegCloseKey(key)
            # key doesn't exist
            pass
    except ImportError:
        # win32 may be not installed...
        pass
else:
    # for posix systems
    DOT_EXE = 'dot'
    path = os.getenv("PATH")
    if path is not None:
      bin_search_path = path.split(":")
Exemple #12
0
def getProgramFilesPath():
    """Get the path to the Program Files folder."""
    keyname = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion'
    currentV = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE,
                                     keyname, 0, win32con.KEY_READ)
    return win32api.RegQueryValueEx(currentV, 'ProgramFilesDir')[0]
Exemple #13
0
def read_value(hive, key, vname=None, use_32bit_registry=False):
    r"""
    Reads a registry value entry or the default value for a key. To read the
    default value, don't pass ``vname``

    Args:

        hive (str): The name of the hive. Can be one of the following:

            - HKEY_LOCAL_MACHINE or HKLM
            - HKEY_CURRENT_USER or HKCU
            - HKEY_USER or HKU
            - HKEY_CLASSES_ROOT or HKCR
            - HKEY_CURRENT_CONFIG or HKCC

        key (str):
            The key (looks like a path) to the value name.

        vname (str):
            The value name. These are the individual name/data pairs under the
            key. If not passed, the key (Default) value will be returned.

        use_32bit_registry (bool):
            Accesses the 32bit portion of the registry on 64bit installations.
            On 32bit machines this is ignored.

    Returns:
        dict: A dictionary containing the passed settings as well as the
            value_data if successful. If unsuccessful, sets success to False.

        bool: Returns False if the key is not found

        If vname is not passed:

            - Returns the first unnamed value (Default) as a string.
            - Returns none if first unnamed value is empty.

    Usage:

        The following will get the value of the ``version`` value name in the
        ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key

        .. code-block:: python

            import salt.utils.win_reg as reg
            reg.read_value(hive='HKLM', key='SOFTWARE\\Salt', vname='version')

    Usage:

        The following will get the default value of the
        ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key

        .. code-block:: python

            import salt.utils.win_reg as reg
            reg.read_value(hive='HKLM', key='SOFTWARE\\Salt')
    """
    # If no name is passed, the default value of the key will be returned
    # The value name is Default

    # Setup the return array
    local_hive = _to_unicode(hive)
    local_key = _to_unicode(key)
    local_vname = _to_unicode(vname)

    ret = {
        "hive": local_hive,
        "key": local_key,
        "vname": local_vname,
        "vdata": None,
        "success": True,
    }

    if not vname:
        ret["vname"] = "(Default)"

    registry = Registry()
    try:
        hkey = registry.hkeys[local_hive]
    except KeyError:
        raise CommandExecutionError("Invalid Hive: {}".format(local_hive))
    access_mask = registry.registry_32[use_32bit_registry]

    try:
        handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
        try:
            # RegQueryValueEx returns and accepts unicode data
            vdata, vtype = win32api.RegQueryValueEx(handle, local_vname)
            if vdata or vdata in [0, "", []]:
                # Only convert text types to unicode
                ret["vtype"] = registry.vtype_reverse[vtype]
                if vtype == win32con.REG_MULTI_SZ:
                    ret["vdata"] = [_to_mbcs(i) for i in vdata]
                elif vtype in [win32con.REG_SZ, win32con.REG_EXPAND_SZ]:
                    ret["vdata"] = _to_mbcs(vdata)
                else:
                    ret["vdata"] = vdata
            else:
                ret["comment"] = "Empty Value"
        except win32api.error as exc:
            if exc.winerror == 2 and vname is None:
                ret["vdata"] = "(value not set)"
                ret["vtype"] = "REG_SZ"
            elif exc.winerror == 2:
                msg = "Cannot find {} in {}\\{}".format(
                    local_vname, local_hive, local_key)
                log.trace(exc)
                log.trace(msg)
                ret["comment"] = msg
                ret["success"] = False
            else:
                raise
    except win32api.error as exc:
        if exc.winerror == 2:
            msg = "Cannot find key: {}\\{}".format(local_hive, local_key)
            log.trace(exc)
            log.trace(msg)
            ret["comment"] = msg
            ret["success"] = False
        else:
            raise
    return ret
Exemple #14
0
def find_graphviz():
    """Locate Graphviz's executables in the system.

    Tries three methods:

    First: Windows Registry (Windows only)
    This requires Mark Hammond's pywin32 is installed.

    Secondly: Search the path
    It will look for 'dot', 'twopi' and 'neato' in all the directories
    specified in the PATH environment variable.

    Thirdly: Default install location (Windows only)
    It will look for 'dot', 'twopi' and 'neato' in the default install
    location under the "Program Files" directory.

    It will return a dictionary containing the program names as keys
    and their paths as values.

    If this fails, it returns None.
    """

    # Method 1 (Windows only)
    #
    if os.sys.platform == 'win32':
        try:
            import win32api, win32con

            # Get the GraphViz install path from the registry
            #
            hkey = win32api.RegOpenKeyEx(
                win32con.HKEY_LOCAL_MACHINE,
                "SOFTWARE\AT&T Research Labs\Graphviz", 0,
                win32con.KEY_QUERY_VALUE)

            path = win32api.RegQueryValueEx(hkey, "InstallPath")[0]
            win32api.RegCloseKey(hkey)

            # Now append the "bin" subdirectory:
            #
            path = os.path.join(path, "bin")
            progs = __find_executables(path)
            if progs is not None:
                # print "Used Windows registry"
                return progs

        except ImportError:
            # Print a messaged suggesting they install these?
            #
            log.debug('The win32api is not installed')
            pass
        except:
            log.debug('Failed to access the registry key')

    # Method 2 (Linux, Windows etc)
    #
    if os.environ.has_key('PATH'):
        for path in os.environ['PATH'].split(os.pathsep):
            progs = __find_executables(path)
            if progs is not None:
                return progs

    # Method 3 (Windows only)
    #
    if os.sys.platform == 'win32':
        # Try and work out the equivalent of "C:\Program Files" on this
        # machine (might be on drive D:, or in a different language)
        #
        if os.environ.has_key('PROGRAMFILES'):
            # Note, we could also use the win32api to get this
            # information, but win32api may not be installed.

            path = os.path.join(os.environ['PROGRAMFILES'], 'ATT', 'GraphViz',
                                'bin')

        else:
            # Just in case, try the default...
            path = r"C:\Program Files\att\Graphviz\bin"

        progs = __find_executables(path)

        if progs is not None:
            # print "Used default install location"
            return progs

    for path in ('/usr/bin', '/usr/local/bin', '/opt/local/bin', '/opt/bin',
                 '/sw/bin', '/usr/share',
                 '/Applications/Graphviz.app/Contents/MacOS/'):
        progs = __find_executables(path)
        if progs is not None:
            # print "Used path"
            return progs

    # Failed to find GraphViz
    #
    return None
Exemple #15
0
 def test_Registry_set_value_multi (self):
   registry.registry (TEST_KEY).set_value ("winsys4", ['a', 'b', 'c'])
   assert win32api.RegQueryValueEx (win32api.RegOpenKey (win32con.HKEY_CURRENT_USER, r"software\winsys"), "winsys4") == (['a', 'b', 'c'], win32con.REG_MULTI_SZ)
Exemple #16
0
		try:
			k = win32api.RegEnumKey(hkey, index)
			index+= 1
			
			keys[k] = "1.0.0.0"
		except Exception,e:
			#print "error: ",e
			break
	win32api.RegCloseKey(hkey)
	
	for k in keys.keys():
		p = r"%s\%s"%(path, k)
		hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, p, 0, win32con.KEY_QUERY_VALUE | win32con.KEY_WOW64_64KEY)
		
		try:
			(version, _) = win32api.RegQueryValueEx(hkey, "Version")
		except Exception:
			Logger.exception("getActiveSetupKeys")
			win32api.RegCloseKey(hkey)
			continue
		
		win32api.RegCloseKey(hkey)
		
		keys[k] = version
	
	return keys


def disableActiveSetup22(rootPath):
	path = r"%s\Software\Microsoft\Active Setup"%(rootPath)
	hkey = win32api.RegOpenKey(win32con.HKEY_USERS, path, 0, win32con.KEY_ALL_ACCESS | win32con.KEY_WOW64_64KEY)
Exemple #17
0
    def browseFile(self, inDemos=0):
        "Display a FileDialog and select a file"
        if inDemos:
            import os
            try:
                import orngConfiguration
                startfile = orngConfiguration.datasetsPath
            except:
                startfile = ""

            if not startfile or not os.path.exists(startfile):
                try:
                    import win32api, win32con
                    t = win32api.RegOpenKey(
                        win32con.HKEY_LOCAL_MACHINE,
                        "SOFTWARE\\Python\\PythonCore\\%i.%i\\PythonPath\\Orange"
                        % sys.version_info[:2], 0, win32con.KEY_READ)
                    t = win32api.RegQueryValueEx(t, "")[0]
                    startfile = t[:t.find("orange")] + "orange\\doc\\datasets"
                except:
                    startfile = ""

            if not startfile or not os.path.exists(startfile):
                d = OWGUI.__file__
                if d[-8:] == "OWGUI.py":
                    startfile = d[:-22] + "doc/datasets"
                elif d[-9:] == "OWGUI.pyc":
                    startfile = d[:-23] + "doc/datasets"

            if not startfile or not os.path.exists(startfile):
                d = os.getcwd()
                if d[-12:] == "OrangeCanvas":
                    startfile = d[:-12] + "doc/datasets"
                else:
                    if d[-1] not in ["/", "\\"]:
                        d += "/"
                    startfile = d + "doc/datasets"

            if not os.path.exists(startfile):
                QMessageBox.information(
                    None, "File",
                    "Cannot find the directory with example data sets",
                    QMessageBox.Ok + QMessageBox.Default)
                return
        else:
            if len(self.recentFiles) == 0 or self.recentFiles[0] == "(none)":
                if sys.platform == "darwin":
                    startfile = os.path.expanduser("~")
                else:
                    startfile = "."
            else:
                startfile = self.recentFiles[0]

        filename = str(
            QFileDialog.getOpenFileName(self, 'Open Orange Data File',
                                        startfile, self.dlgFormats))

        if filename == "":
            return
        if filename in self.recentFiles: self.recentFiles.remove(filename)
        self.recentFiles.insert(0, filename)
        self.setFileList()

        self.openFile(self.recentFiles[0], 0, self.symbolDK, self.symbolDC)
Exemple #18
0
 def test_Registry_set_value_expand_odd_percent (self):
   registry.registry (TEST_KEY).set_value ("winsys4", "50%")
   assert win32api.RegQueryValueEx (win32api.RegOpenKey (win32con.HKEY_CURRENT_USER, r"software\winsys"), "winsys4") == ("50%", win32con.REG_SZ)
Exemple #19
0
def value_exists(hive, key, vname, use_32bit_registry=False):
    """
    Check that the value/data pair is found in the registry.

    .. versionadded:: 2018.3.4

    Args:

        hive (str): The hive to connect to

        key (str): The key to check in

        vname (str): The name of the value/data pair you're checking

        use_32bit_registry (bool): Look in the 32bit portion of the registry

    Returns:
        bool: True if exists, otherwise False

    Usage:

        .. code-block:: python

            import salt.utils.win_reg as reg
            reg.value_exists(hive='HKLM',
                                key='SOFTWARE\\Microsoft\\Windows\\CurrentVersion',
                                vname='CommonFilesDir')
    """
    local_hive = _to_unicode(hive)
    local_key = _to_unicode(key)
    local_vname = _to_unicode(vname)

    registry = Registry()
    try:
        hkey = registry.hkeys[local_hive]
    except KeyError:
        raise CommandExecutionError("Invalid Hive: {}".format(local_hive))
    access_mask = registry.registry_32[use_32bit_registry]

    try:
        handle = win32api.RegOpenKeyEx(hkey, local_key, 0, access_mask)
    except win32api.error as exc:
        if exc.winerror == 2:
            # The key containing the value/data pair does not exist
            return False
        raise

    try:
        # RegQueryValueEx returns and accepts unicode data
        _, _ = win32api.RegQueryValueEx(handle, local_vname)
        # value/data pair exists
        return True
    except win32api.error as exc:
        if exc.winerror == 2 and vname is None:
            # value/data pair exists but is empty
            return True
        else:
            # value/data pair not found
            return False
    finally:
        win32api.RegCloseKey(handle)
Exemple #20
0
 def test_Registry_set_value_non_empty_string (self):
   registry.registry (TEST_KEY).set_value ("winsys4", "winsys")
   assert win32api.RegQueryValueEx (win32api.RegOpenKey (win32con.HKEY_CURRENT_USER, r"software\winsys"), "winsys4") == ("winsys", win32con.REG_SZ)
Exemple #21
0
def EnumTypeLib():
    ret = []
    libKeys = []
    key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
    try:
        num = 0
        while 1:
            try:
                keyName = win32api.RegEnumKey(key, num)
                #print keyName
            except win32api.error:
                break
            # Enumerate all version info
            subKey = win32api.RegOpenKey(key, keyName)
            name = None
            try:
                subNum = 0
                bestVersion = 0.0
                while 1:
                    try:
                        versionStr = win32api.RegEnumKey(subKey, subNum)
                    except win32api.error:
                        break
                    try:
                        versionFlt = float(versionStr)
                    except ValueError:
                        versionFlt = 0 # ????
                    if versionFlt > bestVersion:
                        bestVersion = versionFlt
                        name = win32api.RegQueryValue(subKey, versionStr)
                    subNum = subNum + 1
            finally:
                win32api.RegCloseKey(subKey)
            if name is not None:
                libKeys.append((keyName, versionStr))
                #print name
            num += 1
    except:
        pass

    for keyName, versionStr in libKeys:
        key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib\\%s\\%s" % (keyName, versionStr))
        num = 0
        while True:
            try:
                subKey = win32api.RegEnumKey(key, num)

                #print subKey
            except:
                break
            hSubKey = win32api.RegOpenKey(key, subKey)
            try:
                value, typ = win32api.RegQueryValueEx(hSubKey, None)
                if typ == win32con.REG_EXPAND_SZ:
                    value = win32api.ExpandEnvironmentStrings(value)
            except:
                value = ""
            if subKey=="HELPDIR":
                helpPath = value
            elif subKey.lower()=="flags":
                flags = value
            else:
                try:
                    lcid = int(subKey)
                    #print key
                    #print key, subKey
                    lcidkey = win32api.RegOpenKey(key, subKey)
                    #print lcidkey
                    # Enumerate the platforms
                    lcidnum = 0
                    while 1:
                        try:
                            platform = win32api.RegEnumKey(lcidkey, lcidnum)
                            #print platform
                        except Exception, e:
                            #print 111,e
                            break
                        try:
                            hplatform = win32api.RegOpenKey(lcidkey, platform)
                            fname, typ = win32api.RegQueryValueEx(hplatform, None)
                            if fname != None:
                                ret.append((fname, keyName))
                                #print key2
                            #print fname
                            #print lcid, platform, fname

                            #if typ == win32con.REG_EXPAND_SZ:
                                #fname = win32api.ExpandEnvironmentStrings(fname)
                                #print fname
                        except win32api.error:
                            fname = ""
                        #collected.append((lcid, platform, fname))
                        lcidnum = lcidnum + 1
                    win32api.RegCloseKey(lcidkey)
                except ValueError,e:
                    #print e
                    pass
            num += 1
Exemple #22
0
 def test_Registry_set_value_default (self):
   registry.registry (TEST_KEY).set_value ("", "test")
   assert win32api.RegQueryValueEx (win32api.RegOpenKey (win32con.HKEY_CURRENT_USER, r"software\winsys"), None) == ("test", win32con.REG_SZ)
Exemple #23
0
def system_information():
    """
    Report system versions.
    """
    def system_version():
        """
        Return host system version.
        """
        lin_ver = linux_distribution()
        mac_ver = platform.mac_ver()
        win_ver = platform.win32_ver()

        if lin_ver[0]:
            return " ".join(lin_ver)
        elif mac_ver[0]:
            if isinstance(mac_ver[1], (tuple, list)) and "".join(mac_ver[1]):
                return " ".join([mac_ver[0], ".".join(mac_ver[1]), mac_ver[2]])
            else:
                return " ".join([mac_ver[0], mac_ver[2]])
        elif win_ver[0]:
            return " ".join(win_ver)
        else:
            return ""

    if platform.win32_ver()[0]:
        # Get the version and release info based on the Windows Operating
        # System Product Name. As long as Microsoft maintains a similar format
        # this should be future proof
        import win32api  # pylint: disable=3rd-party-module-not-gated
        import win32con  # pylint: disable=3rd-party-module-not-gated

        # Get the product name from the registry
        hkey = win32con.HKEY_LOCAL_MACHINE
        key = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
        value_name = "ProductName"
        reg_handle = win32api.RegOpenKey(hkey, key)

        # Returns a tuple of (product_name, value_type)
        product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name)

        version = "Unknown"
        release = ""
        if "Server" in product_name:
            for item in product_name.split(" "):
                # If it's all digits, then it's version
                if re.match(r"\d+", item):
                    version = item
                # If it starts with R and then numbers, it's the release
                # ie: R2
                if re.match(r"^R\d+$", item):
                    release = item
            release = "{0}Server{1}".format(version, release)
        else:
            for item in product_name.split(" "):
                # If it's a number, decimal number, Thin or Vista, then it's the
                # version
                if re.match(r"^(\d+(\.\d+)?)|Thin|Vista$", item):
                    version = item
            release = version

        _, ver, service_pack, extra = platform.win32_ver()
        version = " ".join([release, ver, service_pack, extra])
    else:
        version = system_version()
        release = platform.release()

    system = [
        ("system", platform.system()),
        ("dist", " ".join(linux_distribution(full_distribution_name=False))),
        ("release", release),
        ("machine", platform.machine()),
        ("version", version),
        ("locale", __salt_system_encoding__),
    ]

    for name, attr in system:
        yield name, attr
        continue
Exemple #24
0
 def get_value(self, value_name):
     """get value by name"""
     key = self.get_key()
     value, value_type = win32api.RegQueryValueEx(key, value_name)
     return value, value_type
Exemple #25
0
 def __getitem__(self, name):
     value, type = win32api.RegQueryValueEx(self.handle, name)
     if type == win32con.REG_MULTI_SZ:
         return tuple(value)
     return value
Exemple #26
0
    def find(self, searchPath=[]):
        """Look in the usual places for the Library XML file

        First check the path(s) given, if any, for the default exported
        file name, Library.xml. Then check the current directory for
        the same filename, and finally, check the default location.

        On Windows, the iTunes library exports to XML as a matter of
        course, even though it apparently uses the binary
        "iTunes 4 Music Library.itl"
        So we look in the current user's "My Documents/My Music/iTunes/"
        folder for "iTunes 4 Music Library.xml"

        On OS X, the location is also fixed. I've added that, but it's
        untested.
        """

        # No joy. Make a list of other places to look.
        import os, sys

        # Try the searchPath first.
        if len(searchPath):
            for item in searchPath:
                if os.path.isfile(item):
                    self.libFile = item
                    return True

        if sys.platform.__contains__('darwin'):
            # Add the OS X default location.
            searchPath.append(
                os.path.join(os.path.expanduser('~'), 'Music', 'iTunes',
                             'iTunes Music Library.xml'))
        else:
            # Default location for "My Documents" is in the User Profile folder
            searchPath.append(
                os.path.join(os.environ['USERPROFILE'], 'My Documents',
                             'My Music', 'iTunes', 'iTunes Music Library.xml'))

            # I moved mine, and I need the registry to find out where.
            # If we can't access the registry, just skip this step.
            try:
                import win32api, win32con
                regkey = win32api.RegOpenKeyEx(
                    win32con.HKEY_CURRENT_USER,
                    'SOFTWARE\\Microsoft\\Windows\\'
                    'CurrentVersion\\Explorer\\'
                    'Shell Folders', 0, win32con.KEY_READ)
                (value, valtype) = win32api.RegQueryValueEx(regkey, 'My Music')
                if valtype == 1:
                    searchPath.append(
                        os.path.join(value, 'iTunes',
                                     'iTunes Music Library.xml'))
            except:
                pass  # Occurit faecam

        for path in searchPath:
            if os.path.isfile(path):
                self.libFile = path
                return True

        # Couldn't find anything
        print "Couldn't find it in the usual places"
        return False
Exemple #27
0
 def GetSubList(self):
     import os
     clsidstr, versionStr = self.myobject
     collected = []
     helpPath = ""
     key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT,
                               "TypeLib\\%s\\%s" % (clsidstr, versionStr))
     win32ui.DoWaitCursor(1)
     try:
         num = 0
         while 1:
             try:
                 subKey = win32api.RegEnumKey(key, num)
             except win32api.error:
                 break
             hSubKey = win32api.RegOpenKey(key, subKey)
             try:
                 value, typ = win32api.RegQueryValueEx(hSubKey, None)
                 if typ == win32con.REG_EXPAND_SZ:
                     value = win32api.ExpandEnvironmentStrings(value)
             except win32api.error:
                 value = ""
             if subKey == "HELPDIR":
                 helpPath = value
             elif subKey == "Flags":
                 flags = value
             else:
                 try:
                     lcid = int(subKey)
                     lcidkey = win32api.RegOpenKey(key, subKey)
                     # Enumerate the platforms
                     lcidnum = 0
                     while 1:
                         try:
                             platform = win32api.RegEnumKey(
                                 lcidkey, lcidnum)
                         except win32api.error:
                             break
                         try:
                             hplatform = win32api.RegOpenKey(
                                 lcidkey, platform)
                             fname, typ = win32api.RegQueryValueEx(
                                 hplatform, None)
                             if typ == win32con.REG_EXPAND_SZ:
                                 fname = win32api.ExpandEnvironmentStrings(
                                     fname)
                         except win32api.error:
                             fname = ""
                         collected.append((lcid, platform, fname))
                         lcidnum = lcidnum + 1
                     win32api.RegCloseKey(lcidkey)
                 except ValueError:
                     pass
             num = num + 1
     finally:
         win32ui.DoWaitCursor(0)
         win32api.RegCloseKey(key)
     # Now, loop over my collected objects, adding a TypeLib and a HelpFile
     ret = []
     #               if helpPath: ret.append(browser.MakeHLI(helpPath, "Help Path"))
     ret.append(HLICLSID(clsidstr))
     for lcid, platform, fname in collected:
         extraDescs = []
         if platform != "win32":
             extraDescs.append(platform)
         if lcid:
             extraDescs.append("locale=%s" % lcid)
         extraDesc = ""
         if extraDescs: extraDesc = " (%s)" % ", ".join(extraDescs)
         ret.append(HLITypeLib(fname, "Type Library" + extraDesc))
     ret.sort()
     return ret
Exemple #28
0
 def get_value(self, v):
     try:
         (data, type) = win32api.RegQueryValueEx(self.get_keyh(), v)
         return data
     except:
         return None
Exemple #29
0
def system_information():
    '''
    Report system versions.
    '''
    def system_version():
        '''
        Return host system version.
        '''
        lin_ver = linux_distribution()
        mac_ver = platform.mac_ver()
        win_ver = platform.win32_ver()

        if lin_ver[0]:
            return ' '.join(lin_ver)
        elif mac_ver[0]:
            if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]):
                return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]])
            else:
                return ' '.join([mac_ver[0], mac_ver[2]])
        elif win_ver[0]:
            return ' '.join(win_ver)
        else:
            return ''

    if platform.win32_ver()[0]:
        # Get the version and release info based on the Windows Operating
        # System Product Name. As long as Microsoft maintains a similar format
        # this should be future proof
        import win32api  # pylint: disable=3rd-party-module-not-gated
        import win32con  # pylint: disable=3rd-party-module-not-gated

        # Get the product name from the registry
        hkey = win32con.HKEY_LOCAL_MACHINE
        key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
        value_name = 'ProductName'
        reg_handle = win32api.RegOpenKey(hkey, key)

        # Returns a tuple of (product_name, value_type)
        product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name)

        version = 'Unknown'
        release = ''
        if 'Server' in product_name:
            for item in product_name.split(' '):
                # If it's all digits, then it's version
                if re.match(r'\d+', item):
                    version = item
                # If it starts with R and then numbers, it's the release
                # ie: R2
                if re.match(r'^R\d+$', item):
                    release = item
            release = '{0}Server{1}'.format(version, release)
        else:
            for item in product_name.split(' '):
                # If it's a number, decimal number, Thin or Vista, then it's the
                # version
                if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
                    version = item
            release = version

        _, ver, sp, extra = platform.win32_ver()
        version = ' '.join([release, ver, sp, extra])
    else:
        version = system_version()
        release = platform.release()

    system = [
        ('system', platform.system()),
        ('dist', ' '.join(linux_distribution(full_distribution_name=False))),
        ('release', release),
        ('machine', platform.machine()),
        ('version', version),
        ('locale', __salt_system_encoding__),
    ]

    for name, attr in system:
        yield name, attr
        continue
 def get_desktop():
     key = win32api.RegOpenKey(
         win32con.HKEY_CURRENT_USER,
         r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',
         0, win32con.KEY_READ)
     return win32api.RegQueryValueEx(key, 'Desktop')[0]