Search code examples
python-2.7active-directoryldap

How to get all groups that specific user is member of - python, Active Directory


I'm trying to set filter to get all groups that specific user is member of. I'm using Python, Currently

import traceback
import ldap
try:
    l = ldap.open("192.168.1.1")
    .
    .
    .

    l.simple_bind_s(username, password)
                                        #######################################################################
    f_filterStr = '(objectclass=group)' # Would like to modify this, so I'll not have to make the next loop ...
                                        #######################################################################
    # the next command take some seconds 
    results = l.search_s(dn_recs, ldap.SCOPE_SUBTREE, f_filterStr) 
    for i in results:
        if dict == type(i[1]):
            group_name = i[1].get('name')
            if list == type(group_name):
                group_name = group_name[0];
                search_str = "CN=%s," % username_bare
                if -1 != ("%s" %  i[1].get('member')).find (search_str):
                    print "User belong to this group! %s" % group_name

except Exception,e :
    pass # handle as you wish

Solution

  • I think you are making this much too hard.

    No python expert, but you can easily query Microsoft Active Directory for all groups a user is a member of using a filter like:

    (member:1.2.840.113556.1.4.1941:=(CN=UserName,CN=Users,DC=YOURDOMAIN,DC=NET))\
    

    -jim