List users in a group LDAP python

时间:2017-12-18 06:58:21

标签: python ldap python-ldap

I'm new to LDAP. So I don't really know all my terms and fully understand all the terms yet. However, I'm working on an existing system and all the set up is done. I'm just adding a method to it. I'm trying to write a method in Python using LDAP query. I've played around on LDAP Browser and can see that my query is correct. However, I'm not sure how to put it in a python method to return a list. The method needs to return a list of all the users' username. So far I have:

def getUsersInGroup(self, group):
    searchQuery= //for privacy Im not going to share this
    searchAttribute=["username"]
    results = self.ldap.search_s(self.ldap_root, ldap.SCOP_SUBTREE, 
        searchQuery, searchAttribute)

I'm unsure how to go from here. I don't fully understand what the search_s method returns. I read online that its better to use search_s over search method because the while loop can be avoided. Could you please provide and example of where I can go from here. Thanks.

1 个答案:

答案 0 :(得分:0)

您需要执行类似以下内容的LDAP搜索:

# Find all Groups user is a member of:
import ldap
l = ldap.initialize("ldap://my_host")
l.simple_bind_s("[my_dn]", "[my_pass]")
myfilter = "(member=(CN=UserName,CN=Users,DC=EXAMPLE,DC=COM))"
# for all groups including Nested Groups (Only Microsoft Active Directory)
#     (member:1.2.840.113556.1.4.1941:=CN=UserName,CN=Users,DC=EXAMPLE,DC=COM)
ldap_result = l.search("[BASE_DN]", ldap.SCOPE_SUBTREE, myfilter, None)
res_type, data = l.result(ldap_result, 0)
print(data)

您需要使用用户的完整dn。