python-ldap

3.4.5 · active · verified Thu Apr 09

python-ldap provides a low-level API for implementing LDAP clients, wrapping the OpenLDAP C library. It supports LDAPv3 and offers comprehensive features for interacting with LDAP directories. The current version is 3.4.5, with minor releases for bug fixes and security updates, and major versions typically bringing Python version compatibility and API changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to an LDAP server, perform a simple bind, search for entries, and process the results. It highlights the use of `ldap.initialize`, `simple_bind_s`, and `search` with error handling. Note the explicit encoding of strings to bytes, which is crucial for python-ldap 3.x.

import ldap
import os

# Configure LDAP server details
LDAP_SERVER_URI = os.environ.get('LDAP_SERVER_URI', 'ldap://localhost:389')
LDAP_BIND_DN = os.environ.get('LDAP_BIND_DN', 'cn=admin,dc=example,dc=org')
LDAP_BIND_PASSWORD = os.environ.get('LDAP_BIND_PASSWORD', 'adminpassword')
LDAP_SEARCH_BASE = os.environ.get('LDAP_SEARCH_BASE', 'dc=example,dc=org')
LDAP_SEARCH_FILTER = os.environ.get('LDAP_SEARCH_FILTER', '(objectClass=person)')
LDAP_SEARCH_ATTRIBUTES = ['cn', 'mail']

try:
    # Initialize LDAP connection
    l = ldap.initialize(LDAP_SERVER_URI)
    l.set_option(ldap.OPT_REFERRALS, 0)
    l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)

    # Bind to the directory
    l.simple_bind_s(LDAP_BIND_DN.encode('utf-8'), LDAP_BIND_PASSWORD.encode('utf-8'))
    print(f"Successfully bound to {LDAP_SERVER_URI}")

    # Search the directory
    result_id = l.search(
        LDAP_SEARCH_BASE.encode('utf-8'),
        ldap.SCOPE_SUBTREE,
        LDAP_SEARCH_FILTER.encode('utf-8'),
        LDAP_SEARCH_ATTRIBUTES
    )

    results = []
    while True:
        result_type, result_data = l.result(result_id, 0)
        if not result_data:
            break
        if result_type == ldap.RES_SEARCH_ENTRY:
            for dn, entry in result_data:
                results.append((dn.decode('utf-8'), {k.decode('utf-8'): [v.decode('utf-8') for v in val] for k, val in entry.items()}))
    
    print(f"Found {len(results)} entries:")
    for dn, entry in results:
        print(f"DN: {dn}")
        print(f"  CN: {entry.get('cn')}")
        print(f"  Mail: {entry.get('mail')}")

except ldap.SERVER_DOWN as e:
    print(f"LDAP server down or connection failed: {e}")
except ldap.LDAPError as e:
    print(f"LDAP Error: {e}")
finally:
    # Unbind from the directory
    if 'l' in locals() and l:
        try:
            l.unbind_s()
            print("Unbound from LDAP server.")
        except ldap.LDAPError as e:
            print(f"Error during unbind: {e}")

view raw JSON →