python3-ldap (Renamed to ldap3)

0.9.8.4 · renamed · verified Fri Apr 17

The `python3-ldap` project has been renamed to `ldap3`. This entry documents `python3-ldap` as a deprecated library and strongly advises users to migrate to `ldap3`, which is the actively maintained and current library for interacting with LDAP servers in Python. `ldap3` provides a comprehensive, modern, and high-performance feature set for LDAP client operations, including secure connections (LDAPS/StartTLS), asynchronous operations, and various authentication methods. The current version of `ldap3` is 2.9.1, and it maintains a steady release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to an LDAP server using `ldap3`, bind with simple authentication, and perform a basic search. It's crucial to replace placeholder values with your actual LDAP server details and user credentials. Environment variables are used for sensitive information.

import os
from ldap3 import Server, Connection, AUTH_SIMPLE, STRATEGY_SYNC, GET_DSE_INFO

# Configure LDAP connection details
LDAP_SERVER_IP = os.environ.get('LDAP_SERVER_IP', 'your_ldap_server.example.com')
LDAP_USER_DN = os.environ.get('LDAP_USER_DN', 'cn=admin,dc=example,dc=com') # e.g., 'uid=user,ou=users,dc=example,dc=com'
LDAP_PASSWORD = os.environ.get('LDAP_PASSWORD', 'admin_password')
LDAP_BASE_DN = os.environ.get('LDAP_BASE_DN', 'dc=example,dc=com')

try:
    # Define the LDAP server
    server = Server(LDAP_SERVER_IP, get_info=GET_DSE_INFO)

    # Establish a connection
    conn = Connection(server, user=LDAP_USER_DN, password=LDAP_PASSWORD, authentication=AUTH_SIMPLE)

    # Bind to the server
    if not conn.bind():
        print(f"Error binding to LDAP: {conn.result}")
    else:
        print("Successfully bound to LDAP server.")

        # Perform a search
        search_filter = '(objectClass=person)' # Example filter
        conn.search(LDAP_BASE_DN, search_filter, attributes=['cn', 'mail'])

        print("\nSearch Results:")
        for entry in conn.entries:
            print(f"  CN: {entry.cn}, Mail: {entry.mail}")

    # Unbind from the server
    conn.unbind()
    print("Unbound from LDAP server.")

except Exception as e:
    print(f"An error occurred during LDAP operation: {e}")

view raw JSON →