Search code examples
pythonldapldap-querypython-ldap

Python LDAP How to convert search entry into string


Hey I am relatively new to python and LDAP in general, so I apologize if there are any errors. I am trying to do a basic search query on an open LDAP server to learn the basics of working with LDAP. I am trying to get a single result from the search, but it will not let me convert it into a string. There is also a bunch of additional information I want to get rid off.

import ldap
from ldap.filter import escape_filter_chars

username = "cn=read-only-admin,dc=example,dc=com"
password = "password"
searchWord = "boyle"

server = ldap.initialize("ldap://ldap.forumsys.com")
server.simple_bind_s(username, password)

ldap_filter = "(cn=*%s*)" % (ldap.filter.escape_filter_chars(searchWord))
attribute = ['mail']
base = "dc=example,dc=com"
results = server.search_s(

    base,
    ldap.SCOPE_SUBTREE,
    ldap_filter,
    attribute,

)


resultPrint = str(results[0][attribute][0])

print(resultPrint)

Everytime I run this, I get the error "tuple indices must be integers, not list". Also, when I just print the results, it says "[('uid=boyle,dc=example,dc=com', {'mail': ['[email protected]']})]". I just want it to print the email alone. I would appreciate any help. Thanks


Solution

  • The search results are lists of 2-tuples.

    The 2-tuples consist of (dn, entry) with entry being a string-keyed dictionary containing all attributes of the entry the server returned in the search result.

    With LDAP (based on X.500 data model) attributes can be multi-valued and thus even a single attribute value is returned in a list of attribute values.

    So in your particular example:

    >>> result = [('uid=boyle,dc=example,dc=com', {'mail': ['[email protected]']})]
    >>> result[0][1]['mail'][0]
    '[email protected]'
    

    Obviously one wants to loop over the list of search results like this:

    for dn, entry in result:
        mail_addr = entry['mail'][0]