Search code examples
python-3.xactive-directoryldap3

ldap3 add user to group after conn.search


currently, I am writing an AWS Lambda function and the idea is, that someone can send an email to a specific address with a username and AD group and it will trigger the function and add this person to the desired group.

I am using the python module ldap3 and the conn.search part is working, aswell as the addUsersInGroup, but only if I run it separately. If I create a script where I already have the cn or dn name of both user and group and use the addUsersInGroup Function it works, but if I do a conn.search somewhere before it somehow can't establish the connection for the add-to-group part.

from ldap3 import Server, Connection, ALL, NTLM, SUBTREE
from ldap3.extend.microsoft.addMembersToGroups import ad_add_members_to_groups as addUsersInGroups
import email
import os
import json


email = "[email protected]"
subject = "username,ad-group"

user = subject.split(",")[0]
group = subject.split(",")[1]

emaildomain = email.split("@")[1]
domaingroup = ["test.com"]
adgroups = ["group1","group2"]

server = Server('serverIP', use_ssl=True, get_info=ALL)

conn = Connection(server, OU, 
password, auto_bind=True)

def find_user():

    user_criteria = "(&(objectClass=user)(sAMAccountName=%s))"%user

    if conn.search("OU", user_criteria):

        result = str(conn.entries)

        user_dn = result.split("-")[0].replace("[DN: ","")

        return user_dn


    return nouser


def find_group():

    group_criteria = "(&(objectClass=group)(sAMAccountName=%s))"%group

    if conn.search("OU", group_criteria):

        result_group = str(conn.entries)

        group_dn = result_group.split("-")[0].replace("[DN: ","")

        return group_dn

    return nogroup


def add_to_group(user,group):

    addUsersInGroups(conn,user,group)



if emaildomain in domaingroup:
    user = find_user()
    group = find_group()

    add_to_group(user,group)

Please note that I had to delete some things off the script for security reasons. The connection to search for a user or group is working and if I run the add-to-group function it works too, but only running it without any search beforehand.

Somehow I have the feeling that making the conn.search blocks the connection for anything search related and if try to use the same connection for something different e.g. adding a user to group, that request gets blocked.

Here is the error I receive:

Error_Message


Solution

  • Found the solution on this website: https://github.com/cannatag/ldap3/issues/442

    You are getting this error probably due to auto_referrals=True in Connection by default. Try to use: conn = Connection(server, "cn=xxx,cn=users,dc=wwww,dc=zzzz,dc=com", "my_pass", auto_bind=True, auto_referrals=False) and do not search and another DC.