Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 320
Lewis Lebentz Avatar asked Dec 04 '25 23:12

Lewis Lebentz


1 Answers

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]),
    ],
)
like image 111
Michael Ströder Avatar answered Dec 07 '25 06:12

Michael Ströder