简体   繁体   中英

How to add user to LDAP group using Python?

I am using Python-LDAP to interact with Active Directory, and struggling to find what code I need to write to add a user into a security group.

I have already written the code to search for the DN of the user and group, I am just unsure as to what function I need to use to add the user in. I came across this:

LDAPObject.add_s(dn, modlist)

So I have the DN already, but when I've searched modlist I get this:

ldap.modlist.addModlist(entry[, ignore_attr_types=[]])

I'm not sure if I need modifyModlist or addModlist, and am unsure of the values I need to send to it.

I thought I would just be able to send the user and group DN to a function and it would add the user to the group... guess it isn't that simple?

Module ldap.modlist just contains convenience functions for generating lists of modifications. You have to call method LDAPObject.modify_s() to actually modify the group entry.

Let's assume you have the user entry's DN in variable user_dn and group_dn is the DN of the group entry and with ldap_conn being your LDAPObject instance.

Then you would simply use:

ldap_conn.modify_s(
    group_dn,
    [
        (ldap.MOD_ADD, 'member', [user_dn]),
    ],
)

Of course you can also remove users and add other users in one modify operation:

ldap_conn.modify_s(
    group_dn,
    [
        (ldap.MOD_ADD, 'member', [user1_dn, user2_dn]),
        (ldap.MOD_DELETE, 'member', [user3_dn, user4_dn]),
    ],
)

I was getting TypeError Tuple_to_LDAPMod(): expected a tuple when I tried to apply the anwser from Michael Ströder. To fix that err, wrap modlist content to the tuple:

ldap_conn.modify_s(
    group_dn,
    [
        (ldap.MOD_ADD, 'member', [user_dn],)
    ],
)

also, make sure user_dn is a bytestring.

I was getting ldap.OBJECT_CLASS_VIOLATION: {'info': u"attribute 'member' not allowed", 'desc': u'Object class violation'}

In our environment each group member (UID) was listed as a memberUid attribute in the groups, hence this worked for us:

ldap_conn.modify_s(
    group_dn,
    [
        (ldap.MOD_ADD, 'memberUid', [<uid>],)
    ],
)

import ldap

conn = ldap.initialize('ldap://127.0.0.1') ldap_base = 'dc=example,dc=local'

#change your DC

#Group dn should be a string

group_dn = 'CN=Group Policy Creator Owners,CN=Users,DC=example,DC=local'

user_dn = b'CN=test1,OU=Users,DC=example,DC=local'

#Note we havent used modlist which is used for key attribute pairs

conn.modify_s( group_dn, [ (ldap.MOD_ADD, 'member', [user_dn],)], )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM