Exemple #1
0
 def test_set_value_unicode(self):
     '''
     Test - set a registry plain text subkey name to a unicode string value
     '''
     vname = 'TestUniccodeString'
     subkey = 'Software\\SaltStackTest'
     test1_success = False
     test2_success = False
     test1_success = win_mod_reg.set_value(
                         'HKEY_LOCAL_MACHINE',
                         subkey,
                         vname,
                         UNICODETEST_WITH_SIGNS
                         )
     # Now use _winreg direct to see if it worked as expected
     if test1_success:
         handle = _winreg.OpenKey(
                     _winreg.HKEY_LOCAL_MACHINE,
                     subkey,
                     0,
                     _winreg.KEY_ALL_ACCESS
                     )
         (current_vdata, dummy_current_vtype) = _winreg.QueryValueEx(handle, vname)
         _winreg.CloseKey(handle)
     test2_success = (current_vdata == UNICODETEST_WITH_SIGNS)
     self.assertTrue(test1_success and test2_success)
Exemple #2
0
 def traverse_registry_tree(hkey, keypath, ret, access_mask):
     key = _winreg.OpenKey(hkey, keypath, 0, access_mask)
     for subkeyname in subkeys(key):
         subkeypath = r'{0}\{1}'.format(keypath, subkeyname)
         ret = traverse_registry_tree(hkey, subkeypath, ret, access_mask)
         ret.append('{0}'.format(subkeypath))
     return ret
Exemple #3
0
def _key_exists(hive, key, use_32bit_registry=False):
    '''
    Check that the key is found in the registry

    :param str hive: The hive to connect to.
    :param str key: The key to check
    :param bool use_32bit_registry: Look in the 32bit portion of the registry

    :return: Returns True if found, False if not found
    :rtype: bool
    '''

    if PY2:
        local_hive = _mbcs_to_unicode(hive)
        local_key = _unicode_to_mbcs(key)
    else:
        local_hive = hive
        local_key = key

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

    try:
        handle = _winreg.OpenKey(hkey, local_key, 0, access_mask)
        _winreg.CloseKey(handle)
        return True
    except WindowsError:  # pylint: disable=E0602
        return False
Exemple #4
0
 def traverse_registry_tree(_hkey, _keypath, _ret, _access_mask):
     _key = _winreg.OpenKey(_hkey, _keypath, 0, _access_mask)
     for subkeyname in subkeys(_key):
         subkeypath = r'{0}\{1}'.format(_keypath, subkeyname)
         _ret = traverse_registry_tree(_hkey, subkeypath, _ret, access_mask)
         _ret.append('{0}'.format(subkeypath))
     return _ret
Exemple #5
0
def delete_key(hkey, path, key, reflection=True):
    '''
    Delete a registry key

    Note: This cannot delete a key with subkeys

    CLI Example:

    .. code-block:: bash

        salt '*' reg.delete_key HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
    '''
    registry = Registry()
    hkey2 = getattr(registry, hkey)
    access_mask = registry.reflection_mask[reflection]

    try:
        handle = _winreg.OpenKey(hkey2, path, 0, access_mask)
        _winreg.DeleteKeyEx(handle, key)
        _winreg.CloseKey(handle)
        return True
    except Exception:
        pass

    try:
        _winreg.DeleteValue(handle, key)
        _winreg.CloseKey(handle)
        return True
    except Exception:
        _winreg.CloseKey(handle)
        return False
Exemple #6
0
def set_key(hkey, path, key, value, vtype='REG_DWORD', reflection=True):
    '''
    Set a registry key
    vtype: http://docs.python.org/2/library/_winreg.html#value-types

    CLI Example:

    .. code-block:: bash

        salt '*' reg.set_key HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version' '0.97' REG_DWORD
    '''
    registry = Registry()
    hkey2 = getattr(registry, hkey)
    access_mask = registry.reflection_mask[reflection]

    try:
        _type = getattr(_winreg, vtype)
    except AttributeError:
        return False

    try:
        handle = _winreg.OpenKey(hkey2, path, 0, access_mask)
        _winreg.SetValueEx(handle, key, 0, _type, value)
        _winreg.CloseKey(handle)
        return True
    except Exception:
        handle = _winreg.CreateKeyEx(hkey2, path, 0, access_mask)
        _winreg.SetValueEx(handle, key, 0, _type, value)
        _winreg.CloseKey(handle)
    return True
Exemple #7
0
def read_value(hive, key, vname=None):
    r'''
    Reads a registry value or the default value for a key.

    :param hive: string
    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 key: string
    The key (looks like a path) to the value name.

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

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

    CLI Example:

    .. code-block:: bash

        salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
    '''

    # Setup the return array
    ret = {
        'hive': hive,
        'key': key,
        'vname': vname,
        'vdata': None,
        'success': True
    }

    # If no name is passed, the default value of the key will be returned
    # The value name is Default
    if not vname:
        ret['vname'] = '(Default)'

    registry = Registry()
    hive = registry.hkeys[hive]

    try:
        handle = _winreg.OpenKey(hive, key)
        value, vtype = _winreg.QueryValueEx(handle, vname)
        if value:
            ret['vdata'] = value
            ret['vtype'] = registry.vtype_reverse[vtype]
        else:
            ret['comment'] = 'Empty Value'
    except WindowsError as exc:  # pylint: disable=E0602
        log.debug(exc)
        ret['comment'] = '{0}'.format(exc)
        ret['success'] = False

    return ret
Exemple #8
0
def list_keys(hive, key=None, use_32bit_registry=False):
    '''
    Enumerates the subkeys in a registry key or hive.

    :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. If a key is
        not passed, the keys under the hive will be returned.

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

    :return: A list of keys/subkeys under the hive or key.
    :rtype: list

    CLI Example:

    .. code-block:: bash

        salt '*' reg.list_keys HKLM 'SOFTWARE'
    '''

    if PY2:
        local_hive = _mbcs_to_unicode(hive)
        local_key = _unicode_to_mbcs(key)
    else:
        local_hive = hive
        local_key = key

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

    subkeys = []
    try:
        handle = _winreg.OpenKey(hkey, local_key, 0, access_mask)

        for i in range(_winreg.QueryInfoKey(handle)[0]):
            subkey = _winreg.EnumKey(handle, i)
            if PY2:
                subkeys.append(_mbcs_to_unicode(subkey))
            else:
                subkeys.append(subkey)

        handle.Close()

    except WindowsError as exc:  # pylint: disable=E0602
        log.debug(exc)
        log.debug('Cannot find key: {0}\\{1}'.format(hive, key))
        return False, 'Cannot find key: {0}\\{1}'.format(hive, key)

    return subkeys
Exemple #9
0
 def _traverse_registry_tree(_hkey, _keypath, _ret, _access_mask):
     '''
     Traverse the registry tree i.e. dive into the tree
     '''
     _key = _winreg.OpenKey(_hkey, _keypath, 0, _access_mask)
     for subkeyname in _subkeys(_key):
         subkeypath = r'{0}\{1}'.format(_keypath, subkeyname)
         _ret = _traverse_registry_tree(_hkey, subkeypath, _ret, access_mask)
         _ret.append('{0}'.format(subkeypath))
     return _ret
Exemple #10
0
def delete_value(hive, key, vname=None, use_32bit_registry=False):
    '''
    Delete 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 deleted.

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

    :return: Returns True if successful, False if not
    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
    '''

    if PY2:
        local_hive = _mbcs_to_unicode(hive)
        local_key = _unicode_to_mbcs(key)
        local_vname = _unicode_to_mbcs(vname)
    else:
        local_hive = hive
        local_key = key
        local_vname = vname

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

    try:
        handle = _winreg.OpenKey(hkey, local_key, 0, access_mask)
        _winreg.DeleteValue(handle, local_vname)
        _winreg.CloseKey(handle)
        broadcast_change()
        return True
    except WindowsError as exc:  # pylint: disable=E0602
        log.error(exc, exc_info=True)
        log.error('Hive: {0}'.format(local_hive))
        log.error('Key: {0}'.format(local_key))
        log.error('ValueName: {0}'.format(local_vname))
        log.error('32bit Reg: {0}'.format(use_32bit_registry))
        return False
def _get_windows_skyline_appdata_dir():  # pylint: disable=invalid-name
    '''
    Return the Skyline AppData directory on Windows.

    This looks like: 'C:\\ProgramData\\National Instruments\\Skyline'
    '''
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, NI_INSTALLERS_REG_PATH, 0,
                        winreg.KEY_READ) as hkey:
        (appdata_dir, _) = winreg.QueryValueEx(hkey,
                                               NI_INSTALLERS_REG_KEY_APP_DATA)
        return os.path.join(appdata_dir, 'Skyline')
Exemple #12
0
def delete_value(hive,
                 key,
                 vname=None,
                 reflection=True,
                 use_32bit_registry=False):
    '''
    Delete 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 deleted.

    :param bool reflection: A boolean value indicating that the value should
      also be set in the Wow6432Node portion of the registry. Only applies to 64
      bit Windows. This setting is ignored for 32 bit Windows.

    .. deprecated:: 2015.8.2
       Use ``use_32bit_registry`` instead. The parameter seems to have no effect
       since Windows 7 / Windows 2008R2 removed support for reflection. This
       parameter will be removed in Boron.

    :return: Returns True if successful, False if not

    :rtype: bool

    CLI Example:

    .. code-block:: bash

        salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
    '''
    registry = Registry()
    hive = registry.hkeys[hive]
    access_mask = registry.registry_32[use_32bit_registry]

    try:
        handle = _winreg.OpenKey(hive, key, 0, access_mask)
        _winreg.DeleteValue(handle, vname)
        _winreg.CloseKey(handle)
        return True
    except WindowsError as exc:  # pylint: disable=E0602
        log.error(exc, exc_info=True)
        return False
Exemple #13
0
    def test_read_reg_unicode(self):
        '''
        Test - Read a registry value from a subkey using Pythen 2 Unicode
        or Pythen 3 Str i.e. Unicode
        '''
        subkey = 'Software\\Microsoft\\Windows NT\\CurrentVersion'
        vname = 'PathName'
        handle = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey, 0,
                                 _winreg.KEY_ALL_ACCESS)
        (current_vdata,
         dummy_current_vtype) = _winreg.QueryValueEx(handle, vname)
        _winreg.CloseKey(handle)

        test_vdata = win_mod_reg.read_value('HKEY_LOCAL_MACHINE', subkey,
                                            vname)['vdata']
        self.assertEqual(test_vdata, current_vdata)
Exemple #14
0
def delete_value(hive, key, vname=None, reflection=True):
    '''
    Deletes a registry value.

    :param hive: string
    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 key: string
    The key (looks like a path) to the value name.

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

    :param reflection: boolean
    A boolean value indicating that the value should also be set in the
    Wow6432Node portion of the registry. Only applies to 64 bit Windows. This
    setting is ignored for 32 bit Windows.

    :return: boolean
    Returns True if successful, False if not

    CLI Example:

    .. code-block:: bash

        salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
    '''
    registry = Registry()
    hive = registry.hkeys[hive]
    access_mask = registry.reflection_mask[reflection]

    try:
        handle = _winreg.OpenKey(hive, key, 0, access_mask)
        _winreg.DeleteValue(handle, vname)
        _winreg.CloseKey(handle)
        return True
    except WindowsError as exc:  # pylint: disable=E0602
        _winreg.CloseKey(handle)
        log.error(exc)
        return False
Exemple #15
0
    def test_read_reg_plain(self):
        '''
        Test - Read a registry value from a subkey using Pythen 2 Strings or
        Pythen 3 Bytes
        '''
        if not PY2:
            self.skipTest('Invalid for Python Version 2')

        subkey = b'Software\\Microsoft\\Windows NT\\CurrentVersion'
        vname = b'PathName'
        handle = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey, 0,
                                 _winreg.KEY_ALL_ACCESS)
        (current_vdata,
         dummy_current_vtype) = _winreg.QueryValueEx(handle, vname)
        _winreg.CloseKey(handle)

        test_vdata = win_mod_reg.read_value(b'HKEY_LOCAL_MACHINE', subkey,
                                            vname)[b'vdata']
        self.assertEqual(test_vdata, current_vdata)
Exemple #16
0
def create_key(hkey, path, key, value=None, reflection=True):
    '''
    Create a registry key

    CLI Example:

    .. code-block:: bash

        salt '*' reg.create_key HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version' '0.97'
    '''
    registry = Registry()
    hkey2 = getattr(registry, hkey)
    access_mask = registry.reflection_mask[reflection]

    try:
        handle = _winreg.OpenKey(hkey2, path, 0, access_mask)
        _winreg.CloseKey(handle)
        return True
    except Exception:
        handle = _winreg.CreateKeyEx(hkey2, path, 0, access_mask)
        if value:
            _winreg.SetValueEx(handle, key, 0, _winreg.REG_DWORD, value)
        _winreg.CloseKey(handle)
    return True
Exemple #17
0
def delete_key_recursive(hive, key, use_32bit_registry=False):
    '''
    .. versionadded:: 2015.5.4

    Delete a registry key to include all subkeys.

    :param 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 key: The key to remove (looks like a path)

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

    :return: A dictionary listing the keys that deleted successfully as well as
        those that failed to delete.
    :rtype: dict

    The following example will remove ``salt`` and all its subkeys from the
    ``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:

    CLI Example:

    .. code-block:: bash

        salt '*' reg.delete_key_recursive HKLM SOFTWARE\\salt
    '''

    if PY2:
        local_hive = _mbcs_to_unicode(hive)
        local_key = _unicode_to_mbcs(key)
    else:
        local_hive = hive
        local_key = key

    # Instantiate the registry object
    registry = Registry()
    hkey = registry.hkeys[local_hive]
    key_path = local_key
    access_mask = registry.registry_32[
        use_32bit_registry] | _winreg.KEY_ALL_ACCESS

    if not _key_exists(local_hive, local_key, use_32bit_registry):
        return False

    if (len(key) > 1) and (key.count('\\', 1) <
                           registry.subkey_slash_check[hkey]):
        log.error(
            'Hive:{0} Key:{1}; key is too close to root, not safe to remove'.
            format(hive, key))
        return False

    # Functions for traversing the registry tree
    def _subkeys(_key):
        '''
        Enumerate keys
        '''
        i = 0
        while True:
            try:
                subkey = _winreg.EnumKey(_key, i)
                yield subkey
                i += 1
            except WindowsError:  # pylint: disable=E0602
                break

    def _traverse_registry_tree(_hkey, _keypath, _ret, _access_mask):
        '''
        Traverse the registry tree i.e. dive into the tree
        '''
        _key = _winreg.OpenKey(_hkey, _keypath, 0, _access_mask)
        for subkeyname in _subkeys(_key):
            subkeypath = r'{0}\{1}'.format(_keypath, subkeyname)
            _ret = _traverse_registry_tree(_hkey, subkeypath, _ret,
                                           access_mask)
            _ret.append('{0}'.format(subkeypath))
        return _ret

    # Get a reverse list of registry keys to be deleted
    key_list = []
    key_list = _traverse_registry_tree(hkey, key_path, key_list, access_mask)
    # Add the top level key last, all subkeys must be deleted first
    key_list.append(r'{0}'.format(key_path))

    ret = {'Deleted': [], 'Failed': []}

    # Delete all sub_keys
    for sub_key_path in key_list:
        try:
            key_handle = _winreg.OpenKey(hkey, sub_key_path, 0, access_mask)
            _winreg.DeleteKey(key_handle, '')
            ret['Deleted'].append(r'{0}\{1}'.format(hive, sub_key_path))
        except WindowsError as exc:  # pylint: disable=E0602
            log.error(exc, exc_info=True)
            ret['Failed'].append(r'{0}\{1} {2}'.format(hive, sub_key_path,
                                                       exc))

    broadcast_change()

    return ret
Exemple #18
0
def list_values(hive,
                key=None,
                use_32bit_registry=False,
                include_default=True):
    '''
    Enumerates the values in a registry key or hive.

    :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. If a key is
        not passed, the values under the hive will be returned.

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

    :param bool include_default: Toggle whether to include the '(Default)' value.

    :return: A list of values under the hive or key.
    :rtype: list

    CLI Example:

    .. code-block:: bash

        salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
    '''

    if PY2:
        local_hive = _mbcs_to_unicode(hive)
        local_key = _unicode_to_mbcs(key)
    else:
        local_hive = hive
        local_key = key

    registry = Registry()
    hkey = registry.hkeys[local_hive]
    access_mask = registry.registry_32[use_32bit_registry]
    handle = None
    values = list()

    try:
        handle = _winreg.OpenKey(hkey, local_key, 0, access_mask)

        for i in range(_winreg.QueryInfoKey(handle)[1]):
            vname, vdata, vtype = _winreg.EnumValue(handle, i)

            value = {
                'hive': local_hive,
                'key': local_key,
                'vname': vname,
                'vdata': vdata,
                'vtype': registry.vtype_reverse[vtype],
                'success': True
            }
            values.append(value)
        if include_default:
            # Get the default value for the key
            value = {
                'hive': local_hive,
                'key': local_key,
                'vname': '(Default)',
                'vdata': None,
                'success': True
            }
            try:
                # QueryValueEx returns unicode data
                vdata, vtype = _winreg.QueryValueEx(handle, '(Default)')
                if vdata or vdata in [0, '']:
                    value['vtype'] = registry.vtype_reverse[vtype]
                    value['vdata'] = vdata
                else:
                    value['comment'] = 'Empty Value'
            except WindowsError:  # pylint: disable=E0602
                value['vdata'] = ('(value not set)')
                value['vtype'] = 'REG_SZ'
            values.append(value)
    except WindowsError as exc:  # pylint: disable=E0602
        log.debug(exc)
        log.debug(r'Cannot find key: {0}\{1}'.format(hive, key))
        return False, r'Cannot find key: {0}\{1}'.format(hive, key)
    finally:
        if handle:
            handle.Close()
    return values
Exemple #19
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
    if PY2:
        ret = {
            'hive': _mbcs_to_unicode(hive),
            'key': _mbcs_to_unicode(key),
            'vname': _mbcs_to_unicode(vname),
            'vdata': None,
            'success': True
        }
        local_hive = _mbcs_to_unicode(hive)
        local_key = _unicode_to_mbcs(key)
        local_vname = _unicode_to_mbcs(vname)

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

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

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

    try:
        handle = _winreg.OpenKey(hkey, local_key, 0, access_mask)
        try:
            # QueryValueEx returns unicode data
            vdata, vtype = _winreg.QueryValueEx(handle, local_vname)
            if vdata or vdata in [0, '']:
                ret['vtype'] = registry.vtype_reverse[vtype]
                ret['vdata'] = vdata
            else:
                ret['comment'] = 'Empty Value'
        except WindowsError:  # pylint: disable=E0602
            ret['vdata'] = ('(value not set)')
            ret['vtype'] = 'REG_SZ'
    except WindowsError 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 #20
0
def delete_key(hkey,
               path,
               key=None,
               reflection=True,
               force=False,
               use_32bit_registry=False):
    '''
    .. important::
        The name of this function is misleading and will be changed to reflect
        proper usage in the Boron release of Salt. The path option will be removed
        and the key will be the actual key. See the following issue:

        https://github.com/saltstack/salt/issues/25618

        In order to not break existing state files this function will call the
        delete_value function if a key is passed. Key will be passed as the value
        name. If key is not passed, this function will return the default value for
        the key.

        In the Boron release path will be removed and key will be the path.
        reflection will also be removed.

    Delete a registry key

    CLI Example:

    .. code-block:: bash

        salt '*' reg.delete_key HKEY_CURRENT_USER 'SOFTWARE\\Salt'

    :param str hkey: (will be changed to 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 path: (will be changed to key) The key (looks like a path) to
      remove.

    :param str key: (used incorrectly) Will be removed in Boron

    :param bool reflection: A boolean value indicating that the value should
      also be removed from the Wow6432Node portion of the registry. Only applies
      to 64 bit Windows. This setting is ignored for 32 bit Windows.

      Only applies to delete value. If the key parameter is passed, this function
      calls delete_value instead. Will be changed in Boron.

    :param bool force: A boolean value indicating that all subkeys should be
      removed as well. If this is set to False (default) and there are subkeys,
      the delete_key function will fail.

    :return: Returns True if successful, False if not. If force=True, the
      results of delete_key_recursive are returned.

    :rtype: bool
    '''

    if key:  # This if statement will be removed in Boron
        salt.utils.warn_until(
            'Boron', 'Variable names will be changed to match Windows '
            'Registry terminology. These changes will be '
            'made in Boron')
        return delete_value(hive=hkey,
                            key=path,
                            vname=key,
                            reflection=reflection,
                            use_32bit_registry=use_32bit_registry)

    if force:
        return delete_key_recursive(hkey,
                                    path,
                                    use_32bit_registry=use_32bit_registry)

    registry = Registry()
    hive = registry.hkeys[hkey]
    key = path
    access_mask = registry.registry_32[use_32bit_registry]

    try:
        # Can't use delete_value to delete a key
        key_handle = _winreg.OpenKey(hive, key, 0, access_mask)
        _winreg.DeleteKey(key_handle, '')
        _winreg.CloseKey(key_handle)
        return True
    except WindowsError as exc:  # pylint: disable=E0602
        log.error(exc, exc_info=True)
        return False
Exemple #21
0
def delete_key_recursive(hive, key, use_32bit_registry=False):
    '''
    .. versionadded:: 2015.5.4

    Delete a registry key to include all subkeys.

    :param 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 key: The key to remove (looks like a path)

    :return: A dictionary listing the keys that deleted successfully as well as
    those that failed to delete.

    :rtype: dict

    The following example will remove ``salt`` and all its subkeys from the
    ``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:

    CLI Example:

    .. code-block:: bash

        salt '*' reg.delete_key_recursive HKLM SOFTWARE\\salt
    '''
    # Instantiate the registry object
    registry = Registry()
    hkey = registry.hkeys[hive]
    key_path = key
    access_mask = registry.registry_32[use_32bit_registry]

    if not _key_exists(hive, key, use_32bit_registry):
        return False

    # Functions for traversing the registry tree
    def subkeys(key):
        i = 0
        while True:
            try:
                subkey = _winreg.EnumKey(key, i)
                yield subkey
                i += 1
            except WindowsError:  # pylint: disable=E0602
                break

    def traverse_registry_tree(hkey, keypath, ret, access_mask):
        key = _winreg.OpenKey(hkey, keypath, 0, access_mask)
        for subkeyname in subkeys(key):
            subkeypath = r'{0}\{1}'.format(keypath, subkeyname)
            ret = traverse_registry_tree(hkey, subkeypath, ret, access_mask)
            ret.append('{0}'.format(subkeypath))
        return ret

    # Get a reverse list of registry keys to be deleted
    key_list = []
    key_list = traverse_registry_tree(hkey, key_path, key_list, access_mask)
    # Add the top level key last, all subkeys must be deleted first
    key_list.append(r'{0}'.format(key_path))

    ret = {'Deleted': [], 'Failed': []}

    # Delete all sub_keys
    for sub_key_path in key_list:
        try:
            key_handle = _winreg.OpenKey(hkey, sub_key_path, 0, access_mask)
            _winreg.DeleteKey(key_handle, '')
            ret['Deleted'].append(r'{0}\{1}'.format(hive, sub_key_path))
        except WindowsError as exc:  # pylint: disable=E0602
            log.error(exc, exc_info=True)
            ret['Failed'].append(r'{0}\{1} {2}'.format(hive, sub_key_path,
                                                       exc))

    return ret
Exemple #22
0
def read_value(hive, key, vname=None):
    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

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

        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.
    :rtype: dict

    CLI Example:

    .. code-block:: bash

        salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
    '''

    # Setup the return array
    ret = {'hive': hive,
           'key': key,
           'vname': vname,
           'vdata': None,
           'success': True}

    # If no name is passed, the default value of the key will be returned
    # The value name is Default
    if not vname:
        ret['vname'] = '(Default)'

    registry = Registry()
    hkey = registry.hkeys[hive]

    try:
        handle = _winreg.OpenKey(hkey, key)
        try:
            vdata, vtype = _winreg.QueryValueEx(handle, vname)
            if vdata or vdata in [0, '']:
                ret['vtype'] = registry.vtype_reverse[vtype]
                ret['vdata'] = vdata
            else:
                ret['comment'] = 'Empty Value'
        except WindowsError as exc:  # pylint: disable=E0602
            ret['vdata'] = ('(value not set)')
            ret['vtype'] = 'REG_SZ'
            ret['success'] = True
    except WindowsError as exc:  # pylint: disable=E0602
        log.debug(exc)
        log.debug('Cannot find key: {0}\\{1}'.format(hive, key))
        ret['comment'] = 'Cannot find key: {0}\\{1}'.format(hive, key)
        ret['success'] = False

    return ret