Search code examples
pythonldap

Python3 LDAP query to get name and email of a specific group


I would like to get the users' name and email of a specific group when querying an LDAP server using ldap3 Python library. I have been trying the following command, but I am not getting also the email address.

c.search(search_base=LDAP_BASE,search_filter=("(&(objectclass=group)(cn=test-group))"),attributes=["*"])

Any idea how to get have this filter to retrieve the desired data? This query is not retrieving also the email address.

Thank you.


Solution

  • If everyone needs the same query, here is the answer:

    # Firstly find out the DN associated with LDAP group
    c.search(base_dn, '(sAMAccountName="test-group")',
                        search_scope=SUBTREE, attributes=['distinguishedName', 'member'])
    dn_json = json.loads(c.response_to_json())
    distinguished_name = dn_json["entries"][0]["attributes"]["distinguishedName"]
    
    # Retrieve data based on DN
    c.search(base_dn, '(&(objectclass=user)(memberOf={}))'.format(distinguished_name),
                        attributes=["givenName", "sn", "mail"])
    user_data = json.loads(c.response_to_json())
    for index in range(len(user_data["entries"])):
        first_name = user_data["entries"][index]["attributes"]["givenName"]
        surname = user_data["entries"][index]["attributes"]["sn"]
        mail = user_data["entries"][index]["attributes"]["mail"]