Python ldap.modlist() Examples

The following are 13 code examples of ldap.modlist(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ldap , or try the search function .
Example #1
Source File: ldapadmin.py    From diting with GNU General Public License v2.0 7 votes vote down vote up
def ldap_update_user(self, uid, old, new):
        """
        修改dap用户
        :param uid: 用户名
        :param old: 原属性 {'mail': ['admin@example.com']}
        :param new  新属性 {'mail': ['root@example.com']}
        :return: True/None
        """
        result = None
        try:
            obj = self.ldapconn
            obj.protocal_version = ldap.VERSION3
            dn = "uid=%s,%s" % (uid, BASE_DN)
            ldif = modlist.modifyModlist(old, new)
            obj.modify_s(dn, ldif)
            obj.unbind_s()
            result = True
        except ldap.LDAPError as e:
            logger.error("修改用户%s 失败,原因为: %s" % (uid, str(e)))
        return result 
Example #2
Source File: users.py    From core with GNU General Public License v3.0 6 votes vote down vote up
def update_adminsudo(self):
        """Update the user's admin and sudo group settings in LDAP."""
        ldif = conns.LDAP.search_s(
            "cn=admins,ou=groups,{0}".format(self.rootdn),
            ldap.SCOPE_SUBTREE, "(objectClass=*)", None)[0][1]
        memlist = ldif["member"]
        ldif_vals = [(1, "member", None), (0, "member", memlist)]

        if self.admin and b(self.ldap_id) not in memlist:
            memlist += [b(self.ldap_id)]
            conns.LDAP.modify_s(
                "cn=admins,ou=groups,{0}".format(self.rootdn), ldif_vals)
        elif not self.admin and self.ldap_id in memlist:
            memlist.remove(self.ldap_id)
            conns.LDAP.modify_s(
                "cn=admins,ou=groups,{0}".format(self.rootdn), ldif_vals)

        try:
            conns.LDAP.search_s(
                "cn={0},ou=sudo,{1}".format(
                    self.name, self.rootdn),
                ldap.SCOPE_SUBTREE, "(objectClass=*)", None)
            is_sudo = True
        except ldap.NO_SUCH_OBJECT:
            is_sudo = False

        if self.sudo and not is_sudo:
            nldif = {
                "objectClass": [b"sudoRole", b"top"],
                "cn": [b(self.name)],
                "sudoHost": b"ALL",
                "sudoCommand": b"ALL",
                "sudoUser": [b(self.name)],
                "sudoOption": b"authenticate"
            }
            nldif = ldap.modlist.addModlist(nldif)
            conns.LDAP.add_s(
                "cn=" + self.name + ",ou=sudo," + self.rootdn, nldif)
        elif not self.sudo and is_sudo:
            conns.LDAP.delete_s(
                "cn=" + self.name + ",ou=sudo," + self.rootdn) 
Example #3
Source File: groups.py    From core with GNU General Public License v3.0 6 votes vote down vote up
def add(self):
        """Add the group to LDAP."""
        try:
            ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
                                       "(objectClass=*)", None)
            emsg = "A group with this name already exists"
            raise errors.InvalidConfigError(emsg)
        except ldap.NO_SUCH_OBJECT:
            pass
        ldif = {
            "objectClass": [b"posixGroup", b"top"],
            "cn": [b(self.name)],
            "gidNumber": [b(str(self.gid))]
        }
        if self.users:
            ldif["memberUid"] = [b(u) for u in self.users]
        ldif = ldap.modlist.addModlist(ldif)
        signals.emit("groups", "pre_add", self)
        conns.LDAP.add_s(self.ldap_id, ldif)
        signals.emit("groups", "post_add", self) 
Example #4
Source File: users.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def update(self, newpasswd=""):
        """
        Update a user's object in LDAP. Change params on the object first.

        To change password, do so via the ``newpasswd`` param here.

        :param str newpasswd: new password to set
        """
        try:
            ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
                                       "(objectClass=*)", None)
        except ldap.NO_SUCH_OBJECT:
            raise errors.InvalidConfigError(
                "Users", "This user does not exist")

        self.mail = list(set(self.mail))

        for i, x in enumerate(self.mail):
            if not x.endswith(self.domain):
                self.mail[i] = x.split("@")[0] + "@" + self.domain

        ldif = ldif[0][1]
        attrs = {
            "givenName": [b(self.first_name)],
            "sn": [b(self.last_name)] if self.last_name else [b"NONE"],
            "displayName": [b(self.full_name)],
            "cn": [b(self.full_name)],
            "mail": [b(x) for x in self.mail]
        }
        if newpasswd:
            attrs["userPassword"] = [b(ldap_sha512_crypt.encrypt(newpasswd))]
        signals.emit("users", "pre_update", self)
        nldif = ldap.modlist.modifyModlist(ldif, attrs, ignore_oldexistent=1)
        conns.LDAP.modify_s(self.ldap_id, nldif)

        self.update_adminsudo()
        self.update_samba(newpasswd)

        signals.emit(
            "users", "post_update", {"user": self, "passwd": newpasswd}
        ) 
Example #5
Source File: groups.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def update(self):
        """Update a group object in LDAP. Change params on the object first."""
        try:
            ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
                                       "(objectClass=*)", None)
        except ldap.NO_SUCH_OBJECT:
            raise errors.InvalidConfigError("This group does not exist")

        ldif = ldap.modlist.modifyModlist(
            ldif[0][1], {"memberUid": [b(u) for u in self.users]},
            ignore_oldexistent=1)
        signals.emit("groups", "pre_update", self)
        conns.LDAP.modify_s(self.ldap_id, ldif)
        signals.emit("groups", "post_update", self) 
Example #6
Source File: backendAD.py    From ldapcherry with MIT License 5 votes vote down vote up
def _set_password(self, name, password, by_cn=True):
        unicode_pass = '\"' + password + '\"'
        password_value = unicode_pass.encode('utf-16-le')

        ldap_client = self._bind()

        if by_cn:
            dn = self._byte_p2('CN=%(cn)s,%(user_dn)s' % {
                        'cn': name,
                        'user_dn': self.userdn
                       })
        else:
            dn = self._byte_p2(name)

        attrs = {}

        attrs['unicodePwd'] = self._modlist(self._byte_p2(password_value))

        ldif = modlist.modifyModlist({'unicodePwd': 'tmp'}, attrs)
        ldap_client.modify_s(dn, ldif)

        del(attrs['unicodePwd'])
        attrs['UserAccountControl'] = self._modlist(
            self._tobyte(NORMAL_ACCOUNT)
        )
        ldif = modlist.modifyModlist({'UserAccountControl': 'tmp'}, attrs)
        ldap_client.modify_s(dn, ldif) 
Example #7
Source File: backendLdap.py    From ldapcherry with MIT License 5 votes vote down vote up
def add_user(self, attrs):
        """add a user"""
        ldap_client = self._bind()
        # encoding crap
        attrs_srt = self.attrs_pretreatment(attrs)

        attrs_srt[self._byte_p2('objectClass')] = self.objectclasses
        # construct is DN
        dn = \
            self._byte_p2(self.dn_user_attr) + \
            self._byte_p2('=') + \
            self._byte_p2(ldap.dn.escape_dn_chars(
                        attrs[self.dn_user_attr]
                    )
                ) + \
            self._byte_p2(',') + \
            self._byte_p2(self.userdn)
        # gen the ldif first add_s and add the user
        ldif = modlist.addModlist(attrs_srt)
        try:
            ldap_client.add_s(dn, ldif)
        except ldap.ALREADY_EXISTS as e:
            raise UserAlreadyExists(attrs[self.key], self.backend_name)
        except Exception as e:
            ldap_client.unbind_s()
            self._exception_handler(e)
        ldap_client.unbind_s() 
Example #8
Source File: ldapadmin.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def ldap_add_user(self, cn, mail, username, password):
        """
        添加ldap用户
        :param cn: 中文名, mail: 邮箱, username: 用户名, password: 密码
        :return: True/None
        """
        result = None
        try:
            obj = self.ldapconn
            obj.protocal_version = ldap.VERSION3
            password_encrypt = pass_encrypt(password)
            addDN = "uid=%s,%s" % (username, BASE_DN)
            attrs = {}
            attrs['objectclass'] = ['inetOrgPerson'.encode('utf-8')]
            attrs['cn'] = [str(cn).encode('utf-8')]
            # attrs['homeDirectory'] = str('/home/%s' % username)
            # attrs['loginShell'] = '/bin/bash'
            attrs['mail'] = [str(mail).encode('utf-8')]
            attrs['sn'] = [str(username).encode('utf-8')]
            attrs['uid'] = [str(username).encode('utf-8')]
            attrs['userPassword'] = [str(password_encrypt).encode('utf-8')]
            # attrs['uidNumber'] = str(self.__get_max_uidNumber())
            # attrs['gidNumber'] = self.__ldap_getgid(cn='员工')
            ldif = ldap.modlist.addModlist(attrs)
            obj.add_s(addDN, ldif)
            obj.unbind_s()
            result = True
        except ldap.LDAPError as e:
            logger.error("生成用户%s 失败,原因为: %s" % (username, str(e)))
        return result 
Example #9
Source File: ldap_ou_and_role_based_security_groups.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def create_security_group(bind, dn, name):
    dn = 'CN=' + name + ',' + dn
    attrs = {}
    attrs['objectClass'] = ['top', 'group']
    attrs['name'] = name
    # the groupType value may differ between ldap systems
    # this value can be found with an ldap browser
    attrs['groupType'] = '-2147483640'
    attrs['cn'] = name
    attrs['sAMAccountName'] = name
    print(attrs)
    ldif = modlist.addModlist(attrs)
    print(ldif)
    new_security_group = bind.add_s(dn, ldif)
    return new_security_group 
Example #10
Source File: ldap_ou_and_role_based_security_groups.py    From cloudbolt-forge with Apache License 2.0 5 votes vote down vote up
def create_ou(bind, dn, name):
    dn = 'OU=' + name + ',' + dn
    attrs = {}
    attrs['objectClass'] = ['top', 'organizationalUnit']
    attrs['name'] = name
    print(attrs)
    ldif = modlist.addModlist(attrs)
    print(ldif)
    new_ou = bind.add_s(dn, ldif)
    return new_ou 
Example #11
Source File: users.py    From core with GNU General Public License v3.0 4 votes vote down vote up
def add(self, passwd):
        """
        Add the user to LDAP.

        :param str passwd: user password to set
        """
        try:
            ldif = conns.LDAP.search_s(
                self.ldap_id, ldap.SCOPE_BASE, "(objectClass=*)", None)
            msg = "A user named {0} already exists".format(self.name)
            raise errors.InvalidConfigError(msg)
        except ldap.NO_SUCH_OBJECT:
            pass

        # Create LDAP user with proper metadata
        ldif = {
            "objectClass": [b"mailAccount", b"inetOrgPerson", b"posixAccount"],
            "givenName": [b(self.first_name)],
            "sn": [b(self.last_name)] if self.last_name else [b"NONE"],
            "displayName": [b(self.full_name)],
            "cn": [b(self.full_name)],
            "uid": [b(self.name)],
            "mail": [b(self.name + "@" + self.domain)],
            "maildrop": [b(self.name)],
            "userPassword": [b(ldap_sha512_crypt.encrypt(passwd))],
            "gidNumber": [b"100"],
            "uidNumber": [b(str(self.uid))],
            "homeDirectory": [b("/home/" + self.name)],
            "loginShell": [b"/usr/bin/bash"]
            }
        ldif = ldap.modlist.addModlist(ldif)
        signals.emit("users", "pre_add", self)
        logger.debug("Roles", "Adding user: {0}".format(self.ldap_id))
        conns.LDAP.add_s(self.ldap_id, ldif)
        modes = ["admin" if self.admin else "", "sudo" if self.sudo else ""]
        msg = "Setting user modes: {0}".format(", ".join(modes))
        logger.debug("Roles", msg)

        self.update_adminsudo()
        self.update_samba(passwd)

        signals.emit("users", "post_add", {"user": self, "passwd": passwd}) 
Example #12
Source File: backendLdap.py    From ldapcherry with MIT License 4 votes vote down vote up
def set_attrs(self, username, attrs):
        """ set user attributes"""
        ldap_client = self._bind()
        tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
        if tmp is None:
            raise UserDoesntExist(username, self.backend_name)
        dn = self._byte_p2(tmp[0])
        old_attrs = tmp[1]
        for attr in attrs:
            bcontent = self._byte_p2(attrs[attr])
            battr = self._byte_p2(attr)
            new = {battr: self._modlist(self._byte_p3(bcontent))}
            # if attr is dn entry, use rename
            if attr.lower() == self.dn_user_attr.lower():
                ldap_client.rename_s(
                    dn,
                    ldap.dn.dn2str([[(battr, bcontent, 1)]])
                    )
                dn = ldap.dn.dn2str(
                    [[(battr, bcontent, 1)]] + ldap.dn.str2dn(dn)[1:]
                    )
            else:
                # if attr is already set, replace the value
                # (see dict old passed to modifyModlist)
                if attr in old_attrs:
                    if type(old_attrs[attr]) is list:
                        tmp = []
                        for value in old_attrs[attr]:
                            tmp.append(self._byte_p2(value))
                        bold_value = tmp
                    else:
                        bold_value = self._modlist(
                            self._byte_p3(old_attrs[attr])
                        )
                    old = {battr: bold_value}
                # attribute is not set, just add it
                else:
                    old = {}
                ldif = modlist.modifyModlist(old, new)
                if ldif:
                    try:
                        ldap_client.modify_s(dn, ldif)
                    except Exception as e:
                        ldap_client.unbind_s()
                        self._exception_handler(e)

        ldap_client.unbind_s() 
Example #13
Source File: backendLdap.py    From ldapcherry with MIT License 4 votes vote down vote up
def add_to_groups(self, username, groups):
        ldap_client = self._bind()
        # recover dn of the user and his attributes
        tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
        dn = tmp[0]
        attrs = tmp[1]
        attrs['dn'] = dn
        self._normalize_group_attrs(attrs)
        dn = self._byte_p2(tmp[0])
        # add user to all groups
        for group in groups:
            group = self._byte_p2(group)
            # iterate on group membership attributes
            for attr in self.group_attrs:
                # fill the content template
                content = self._byte_p2(self.group_attrs[attr] % attrs)
                self._logger(
                    severity=logging.DEBUG,
                    msg="%(backend)s: adding user '%(user)s'"
                        " with dn '%(dn)s' to group '%(group)s' by"
                        " setting '%(attr)s' to '%(content)s'" % {
                            'user': username,
                            'dn': self._uni(dn),
                            'group': self._uni(group),
                            'attr': attr,
                            'content': self._uni(content),
                            'backend': self.backend_name
                            }
                )
                ldif = modlist.modifyModlist(
                        {},
                        {attr: self._modlist(self._byte_p3(content))}
                       )
                try:
                    ldap_client.modify_s(group, ldif)
                # if already member, not a big deal, just log it and continue
                except (ldap.TYPE_OR_VALUE_EXISTS, ldap.ALREADY_EXISTS) as e:
                    self._logger(
                        severity=logging.INFO,
                        msg="%(backend)s: user '%(user)s'"
                            " already member of group '%(group)s'"
                            " (attribute '%(attr)s')" % {
                                'user': username,
                                'group': self._uni(group),
                                'attr': attr,
                                'backend': self.backend_name
                                }
                    )
                except ldap.NO_SUCH_OBJECT as e:
                    raise GroupDoesntExist(group, self.backend_name)
                except Exception as e:
                    ldap_client.unbind_s()
                    self._exception_handler(e)
        ldap_client.unbind_s()