当前位置: 首页>>代码示例>>Python>>正文


Python ldap3.MODIFY_DELETE属性代码示例

本文整理汇总了Python中ldap3.MODIFY_DELETE属性的典型用法代码示例。如果您正苦于以下问题:Python ldap3.MODIFY_DELETE属性的具体用法?Python ldap3.MODIFY_DELETE怎么用?Python ldap3.MODIFY_DELETE使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在ldap3的用法示例。


在下文中一共展示了ldap3.MODIFY_DELETE属性的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _create_ldap_modify_changes

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def _create_ldap_modify_changes(self, attributes, uid):
        """
        Identifies if an LDAP attribute already exists and if the value needs to be updated, deleted or added.

        :param attributes: Attributes to be updated
        :type attributes: dict
        :param uid: The uid of the user object in the resolver
        :type uid: basestring
        :return: dict with attribute name as keys and values
        """
        modify_changes = {}
        uinfo = self.getUserInfo(uid)

        for fieldname, value in attributes.items():
            if value:
                if fieldname in uinfo:
                    modify_changes[fieldname] = [MODIFY_REPLACE, [value]]
                else:
                    modify_changes[fieldname] = [MODIFY_ADD, [value]]
            else:
                modify_changes[fieldname] = [MODIFY_DELETE, [value]]

        return modify_changes 
开发者ID:privacyidea,项目名称:privacyidea,代码行数:25,代码来源:LDAPIdResolver.py

示例2: remove_user_from_group

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def remove_user_from_group(ldapconnection, data):
        group_dn = data['group_dn']
        user_dn = data['user_dn']

        # Now add the user as a member to this group
        res = ldapconnection.modify(group_dn, {
            'member': [(ldap3.MODIFY_DELETE, [user_dn])]
        })
        if res:
            print_o('Removed membership of %s from %s' % (user_dn, group_dn))
            return True
        else:
            # Unwilling to perform result means we aren't a member
            if ldapconnection.result['result'] == 53:
                print_m('Could not remove %s from group %s since they are not a member, your restore data may be out of date, continuing anyway!' % (user_dn, group_dn))
                # Treat this as a success
                return True
            raise RestoreException('Failed to remove %s from group %s: %s' % (user_dn, group_dn, str(ldapconnection.result))) 
开发者ID:fox-it,项目名称:aclpwn.py,代码行数:20,代码来源:restore.py

示例3: _remove_dn_from_proid_group

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def _remove_dn_from_proid_group(self, conn, server_dn, proid, force=False):
        """Removes a placement.

        :param conn:
            The `ldap3.Connection`
        :param server_dn:
            The server server_dn
        :param proid:
            The name of the proid
        """
        server_dn_set = self._get_server_dn_set(proid)

        if not force:
            if not self._decrement_dn(server_dn_set, server_dn):
                return

        group = self._config.get_group_dn(proid)

        _LOGGER.debug('Removing %r from group %r', server_dn, group)
        conn.modify(group, {'member': [(ldap3.MODIFY_DELETE,
                                        [server_dn])]})

        if not _check_ldap3_operation(conn) and not force:
            self._increment_dn(server_dn_set, server_dn) 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:26,代码来源:gmsa.py

示例4: update_group_members

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def update_group_members(self, cn, members):
        dn = ",".join((f"cn={cn}", self.group_base))

        if members:
            changes = {"memberUid": [(MODIFY_REPLACE, members)]}
        else:
            changes = {"memberUid": [(MODIFY_DELETE, [])]}

        self.connection.modify(dn, changes) 
开发者ID:webkom,项目名称:lego,代码行数:11,代码来源:ldap.py

示例5: delete_spn

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def delete_spn(self, proid, spn):
        """ Remove spn to a GMSA
        """

        gmsa_obj = self._get_gmsa_obj(proid)
        if gmsa_obj:
            self.conn.modify(
                gmsa_obj['dn'],
                {'servicePrincipalName': [(ldap3.MODIFY_DELETE, [spn])]}
            )
            if not _check_ldap3_operation(self.conn):
                raise RuntimeError(self.conn.result['description'])
        else:
            raise RuntimeError('Proid:{} not found'.format(proid)) 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:16,代码来源:gmsa.py

示例6: remove

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def remove(self, dn, entry):
        """Removes attributes from the record."""
        to_be_removed = {
            k: [(ldap3.MODIFY_DELETE, [])] for k in entry.keys()
        }
        self.modify(dn, to_be_removed) 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:8,代码来源:_ldap.py

示例7: increment_attr

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def increment_attr(self, dn, attr, incr=1, use_increment=True):
        import random
        import time

        if use_increment and \
           self.has_control(OID_LDAP_CONTROL_POSTREAD) and \
           self.has_feature(OID_LDAP_FEATURE_MODIFY_INCREMENT):
            # this is far uglier than the Perl version already
            postread_ctrl = ldap3.protocol.rfc4527.post_read_control([attr])
            self.conn.modify(dn,
                             {attr: [(ldap3.MODIFY_INCREMENT, incr)]},
                             controls=[postread_ctrl])
            res = self.conn.result["controls"][OID_LDAP_CONTROL_POSTREAD]["value"]["result"]
            res = CaseInsensitiveDict(res)
            return res[attr][0]

        wait = 0
        while True:
            old_val = self.read_attr(dn, attr)[0]
            new_val = str(int(old_val) + incr)
            try:
                self.conn.modify(dn,
                                 {attr: [(ldap3.MODIFY_DELETE, old_val),
                                         (ldap3.MODIFY_ADD, new_val)]})
            except ldap3.core.exceptions.LDAPNoSuchAttributeResult as e:
                Core.debug("swap (%r, %r) failed: %r", old_val, new_val, e)
                wait += 1
                time.sleep(0.05 * 2**random.randint(0, wait))
            else:
                break
        return int(new_val) 
开发者ID:grawity,项目名称:code,代码行数:33,代码来源:client_ldap3.py

示例8: add_client2script

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def add_client2script(script_inum, client_id):
    dn = 'inum={},ou=scripts,o=gluu'.format(script_inum)

    if persistence_type == 'ldap':
        ldap_conn.search(search_base=dn, search_filter='(objectClass=*)', search_scope=ldap3.BASE, attributes=['oxConfigurationProperty'])
        
        for e in ldap_conn.response[0]['attributes'].get('oxConfigurationProperty', []):
            try:
                oxConfigurationProperty = json.loads(e)
            except:
                continue
            if isinstance(oxConfigurationProperty, dict) and oxConfigurationProperty.get('value1') == 'allowed_clients':
                if not client_id in oxConfigurationProperty['value2']:
                    oxConfigurationProperty['value2'] = add2strlist(client_id, oxConfigurationProperty['value2'])
                    oxConfigurationProperty_js = json.dumps(oxConfigurationProperty)
                    ldap_conn.modify(
                        dn,
                        {'oxConfigurationProperty': [ldap3.MODIFY_DELETE, e]}
                        )
                    ldap_conn.modify(
                        dn,
                        {'oxConfigurationProperty': [ldap3.MODIFY_ADD, oxConfigurationProperty_js]}
                        )
                    break

    else:
        n1ql = 'SELECT oxConfigurationProperty FROM `gluu` USE KEYS "scripts_{}"'.format(script_inum)
        result = setupObj.cbm.exec_query(n1ql)
        js = result.json()

        oxConfigurationProperties = js['results'][0]['oxConfigurationProperty']
        for i, oxconfigprop_str in enumerate(oxConfigurationProperties):
            oxconfigprop = json.loads(oxconfigprop_str)
            if oxconfigprop.get('value1') == 'allowed_clients' and not client_id in oxconfigprop['value2']:
                oxconfigprop['value2'] = self.add2strlist(client_id, oxconfigprop['value2'])
                oxConfigurationProperties[i] = json.dumps(oxconfigprop)
                break
        else:
            return

        n1ql = 'UPDATE `gluu` USE KEYS "scripts_{}" SET `oxConfigurationProperty`={}'.format(script_inum, json.dumps(oxConfigurationProperties))
        setupObj.cbm.exec_query(n1ql) 
开发者ID:GluuFederation,项目名称:community-edition-setup,代码行数:44,代码来源:post-setup-add-components.py

示例9: _diff_entries

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def _diff_entries(old_entry, new_entry):
    """Diff the entries and produce a diff dictionary suitable for update."""
    # Adapted from python-ldap (http://www.python-ldap.org/) modlist
    # https://github.com/pyldap/pyldap/blob/master/Lib/ldap/modlist.py#L51
    diff = {}
    attrtype_lower_map = {}
    for attr in old_entry.keys():
        attrtype_lower_map[attr.lower()] = attr
    for attrtype in new_entry.keys():
        attrtype_lower = attrtype.lower()
        # Filter away null-strings
        new_values = [
            value
            for value in new_entry[attrtype]
            if value is not None
        ]
        if attrtype_lower in attrtype_lower_map:
            old_values = old_entry.get(attrtype_lower_map[attrtype_lower], [])
            old_values = [
                value
                for value in old_values
                if value is not None
            ]
            del attrtype_lower_map[attrtype_lower]
        else:
            old_values = []

        if not old_values and new_values:
            # Add a new attribute to entry
            diff.setdefault(attrtype, []).append(
                (ldap3.MODIFY_ADD, new_values)
            )
        elif old_values and new_values:
            # Replace existing attribute
            if _diff_attribute_values(old_values, new_values):
                diff.setdefault(attrtype, []).append(
                    (ldap3.MODIFY_REPLACE, new_values))
        elif old_values and not new_values:
            # Completely delete an existing attribute
            diff.setdefault(attrtype, []).append(
                (ldap3.MODIFY_DELETE, []))

    # Remove all attributes of old_entry which are not present
    # in new_entry at all
    for attr in attrtype_lower_map:
        attrtype = attrtype_lower_map[attr]
        diff.setdefault(attrtype, []).append((ldap3.MODIFY_DELETE, []))

    return diff 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:51,代码来源:_ldap.py

示例10: update_schema

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def update_schema(self, new_schema):
        """Safely update schema, preserving existing attribute types."""
        old_schema = self.schema() or self.init_schema()

        schema_dn = old_schema['dn']
        old_attr_types = old_schema['attributeTypes']
        new_attr_types = new_schema['attributeTypes']

        changes = collections.defaultdict(list)
        to_del, to_add = self._schema_attrtype_diff(old_attr_types,
                                                    new_attr_types)

        if to_del:
            values = [_attrtype_2_str(_abstract_2_attrtype(name, attr))
                      for name, attr in six.iteritems(to_del)]
            _LOGGER.debug('del: %s - olcAttributeTypes: %r', schema_dn, values)
            changes['olcAttributeTypes'].extend(
                [(ldap3.MODIFY_DELETE, values)])

        if to_add:
            values = [_attrtype_2_str(_abstract_2_attrtype(name, attr))
                      for name, attr in six.iteritems(to_add)]
            _LOGGER.debug('add: %s - olcAttributeTypes: %r', schema_dn, values)
            changes['olcAttributeTypes'].extend([(ldap3.MODIFY_ADD, values)])

        old_obj_classes = old_schema['objectClasses']
        new_obj_classes = new_schema['objectClasses']

        to_del, to_add = self._schema_objcls_diff(old_obj_classes,
                                                  new_obj_classes)
        if to_del:
            values = [_objcls_2_str(name, item)
                      for name, item in six.iteritems(to_del)]
            _LOGGER.debug('del: %s - olcObjectClasses: %r', schema_dn, values)
            changes['olcObjectClasses'].extend([(ldap3.MODIFY_DELETE, values)])
        if to_add:
            values = [_objcls_2_str(name, item)
                      for name, item in six.iteritems(to_add)]
            _LOGGER.debug('add: %s - olcObjectClasses: %r', schema_dn, values)
            changes['olcObjectClasses'].extend([(ldap3.MODIFY_ADD, values)])

        if changes:
            # TODO must be modified in a specific order to avoid exceptions
            self.modify(schema_dn, changes)
        else:
            _LOGGER.info('Schema is up to date.') 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:48,代码来源:_ldap.py

示例11: test_on_deleted_placement

# 需要导入模块: import ldap3 [as 别名]
# 或者: from ldap3 import MODIFY_DELETE [as 别名]
def test_on_deleted_placement(self, connection):
        """Test gmsa.HostGroupWatch._on_deleted_placement."""
        # Access protected module
        # pylint: disable=W0212
        server1_path = os.path.join(self.placement_dir, 'server1.ad.com')
        os.mkdir(server1_path)
        placement_path = os.path.join(server1_path, 'proid1.app#0000000000001')
        utils.touch(placement_path)

        with io.open(os.path.join(self.servers_dir, 'server1.ad.com'),
                     'w') as f:
            yaml.dump({
                servers.DC_KEY: 'dc.ad.com',
                servers.DN_KEY: 'CN=server1,DC=AD,DC=COM',
                'partition': 'partition1'
            }, f)

        mock_connection = mock.MagicMock()
        connection.return_value = mock_connection
        type(mock_connection).result = mock.PropertyMock(side_effect={
            'result': 0
        })
        type(mock_connection).response = mock.PropertyMock(return_value=[
            {'attributes': {
                'samAccountName': 'proid1-gmsa-hosts',
                'member': ['CN=server1,DC=AD,DC=COM']
            }}
        ])

        watch = gmsa.HostGroupWatch(self.root, 'partition1',
                                    'OU=test,DC=ad,DC=com', '{}-gmsa-hosts')
        watch._sync()

        self.assertEqual(watch._proids, {
            'proid1': {'CN=server1,DC=AD,DC=COM': 1},
        })

        os.remove(placement_path)
        watch._on_deleted_placement(placement_path)

        self.assertEqual(watch._proids, {
            'proid1': {'CN=server1,DC=AD,DC=COM': 0},
        })

        mock_connection.modify.assert_has_calls([
            mock.call('CN=proid1-gmsa-hosts,OU=test,DC=ad,DC=com',
                      {'member': [(ldap3.MODIFY_DELETE,
                                   ['CN=server1,DC=AD,DC=COM'])]}),
        ]) 
开发者ID:Morgan-Stanley,项目名称:treadmill,代码行数:51,代码来源:gmsa_test.py


注:本文中的ldap3.MODIFY_DELETE属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。