Use ldap3 to query all active directory groups a user belongs to

zs2020 picture zs2020 · Mar 18, 2015 · Viewed 11.2k times · Source

I have no problem to query the domain user from active directory with this query

from ldap3 import ObjectDef, AttrDef, Reader, Entry, Attribute, OperationalAttribute
import ldap3

person = ObjectDef('inetOrgPerson')
s = ldap3.Server('myad.com')
c = ldap3.Connection(s, user = 'myuser', password = 'mypassword')

ldap3.Reader(c, person, '(&(objectCategory=person)(sAMAccountName=myuser))', 'dc=mydomain,dc=com').search()

however, this query returns empty list of groups the user belongs to, how to make it work?

ldap3.Reader(c, person, '(&(objectCategory=group)(member=myuser))', 'dc=mydomain,dc=com').search()

I use ldap3. Thanks in advance.

Answer

zs2020 picture zs2020 · Mar 18, 2015

This answer helped me:

I need the full DN of the user returned from the first query, so this works:

ldap3.Reader(c, person, '(&(member=CN=myuser_in_full_name,OU=xxx,OU=xxxxxx,DC=mydomain,DC=com)(objectClass=group))', 'dc=mydomain,dc=com').search()