Search code examples
pythonpython-3.xactive-directoryldapldap3

Space in OU causing ldap search to fail


I'm using ldap3 library in python3.9 to get all the members and manager details including manager's displayName and Email of specific AD groups into a list with a loop.

conn.search(search_base='OU=Groups,OU=US,DC=local,DC=test,DC=org',
    search_filter='(&(objectClass=group)(cn=AD-GROUP-NAME))',
    attributes=['managedBy','member'],
    search_scope='SUBTREE'
    )

I pass the results for each member in the above results into a new search :

for entry in conn.entries:
    for member in entry.managedBy:
        conn.search(
            search_base=member.split(",",2)[2], # Removes Fname & LName from distinguishedName
            search_filter=f'(distinguishedName={member})',
            attributes=['sAMAccountName','mail','displayName']
            )

The second search works for most of the members except where there is a space in on of the OU as below in the manager's distinguishedName:

CN=LName, FName,OU=Admin Accounts,OU=Management,OU=US,DC=local,DC=test,DC=org

I have tried to escape this using using \ or \\ even replacing the space with 20 but couldn't get it to work.

Thanks.


Solution

  • Since you already have a DN, it may be less problematic and more performant to read this object directly, like so:

    for entry in conn.entries:
        for member in entry.managedBy:
            conn.search(
                search_base=member,
                search_filter='(objectClass=*)',
                search_scope=BASE,
                attributes=['sAMAccountName','mail','displayName']
                )