Registry / auth-security / ldap3
library2.9.1pypypi✓ verified 25d ago

ldap3 is a strictly RFC 4510 conforming LDAP V3 pure Python client library. The same codebase runs in Python 2, Python 3, PyPy and PyPy3. It offers a more pythonic way to interact with LDAP servers, including an Abstraction Layer for simplified operations.

pip install ldap3
INSTALL
IMPORT
SIG · LDAP3
L
ldap3
auth-securitypythonv2.9.1
Install
1.8s avg
Import
265ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.9.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.915 runs
installs and imports cleanly · install 0.0s · import 0.271s · 23.1MB
glibc
py 3.103.915 runs
installs and imports cleanly · install 1.8s · import 0.260s · 24MB
21MB installed
● package 21MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Server
from ldap3 import Server
Connection
from ldap3 import Connection
Tls
from ldap3 import Tls
ANONYMOUS
from ldap3 import ANONYMOUS
from ldap3 import AUTH_ANONYMOUS
Constants like ANONYMOUS, SIMPLE, SASL are directly in the ldap3 namespace, not under an 'AUTH_' prefix.
STRATEGY_SYNC
from ldap3 import SYNC
from ldap3 import STRATEGY_SYNC
Connection strategies are typically imported directly by their short names (e.g., SYNC, ASYNC, RESTARTABLE).

This example demonstrates how to establish a connection to an LDAP server, perform a simple bind with credentials (or anonymously), and execute a search operation. It uses environment variables for sensitive configuration details. The `raise_exceptions=True` parameter is added to the `Connection` to ensure LDAP operation failures are surfaced as Python exceptions.

import os from ldap3 import Server, Connection, SYNC, ANONYMOUS, SUBTREE # Configuration from environment variables for security and flexibility 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=com') LDAP_BIND_PASSWORD = os.environ.get('LDAP_BIND_PASSWORD', 'adminpassword') LDAP_SEARCH_BASE = os.environ.get('LDAP_SEARCH_BASE', 'dc=example,dc=com') LDAP_SEARCH_FILTER = os.environ.get('LDAP_SEARCH_FILTER', '(objectClass=person)') LDAP_SEARCH_ATTRIBUTES = os.environ.get('LDAP_SEARCH_ATTRIBUTES', 'cn,mail').split(',') def ldap_connect_and_search(): try: # Define the LDAP server s = Server(LDAP_SERVER_URI) # Establish a connection. auto_bind=True performs the bind operation immediately. # authentication=ANONYMOUS can be used if no credentials are required. # For authenticated bind: # c = Connection(s, user=LDAP_BIND_DN, password=LDAP_BIND_PASSWORD, client_strategy=SYNC, auto_bind=True) c = Connection(s, user=LDAP_BIND_DN, password=LDAP_BIND_PASSWORD, client_strategy=SYNC, auto_bind=True, raise_exceptions=True) print(f"Connection status: {c.bound}") # Perform a search operation # search_base: The base DN for the search # search_filter: The LDAP filter string # search_scope: The scope of the search (e.g., SUBTREE, BASE, LEVEL) # attributes: List of attributes to retrieve, or ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES c.search(LDAP_SEARCH_BASE, LDAP_SEARCH_FILTER, search_scope=SUBTREE, attributes=LDAP_SEARCH_ATTRIBUTES) # Process the search results print(f"Found {len(c.entries)} entries:") for entry in c.entries: print(f" DN: {entry.entry_dn}") for attr in LDAP_SEARCH_ATTRIBUTES: if hasattr(entry, attr): print(f" {attr}: {getattr(entry, attr).value}") except Exception as e: print(f"An LDAP error occurred: {e}") finally: if 'c' in locals() and c.bound: c.unbind() print("Connection unbound.") if __name__ == '__main__': ldap_connect_and_search()
Debug
Known issues
gotchaThe library was formerly known as `python3-ldap` and was renamed to `ldap3` to avoid confusion with the `python-ldap` library. Users migrating from `python3-ldap` or older `python-ldap` installations should be aware.
fix
Ensure you are installing and importing the `ldap3` package. If you have `python-ldap` installed, be mindful of potential conflicts due to similar names but different APIs.
affects: < 1.0
gotchaLDAP protocol strictly uses UTF-8 for string values. While `ldap3` attempts to handle encoding, mismatches between your environment's default encoding and required UTF-8 can lead to issues. Explicit encoding/decoding may be necessary.
fix
Be explicit about string encoding when necessary. Use `set_config_parameter('DEFAULT_ENCODING', 'my_encoding')` if your input encoding is not UTF-8 and differs from your system default. Ensure data retrieved is handled as UTF-8.
affects: All
gotchaDifferent connection strategies (e.g., `SYNC`, `ASYNC`, `RESTARTABLE`, `REUSABLE`, `SAFE_SYNC`, `SAFE_RESTARTABLE`) have different return value semantics. Synchronous strategies (e.g., `SYNC`) typically return booleans for success/failure, while asynchronous strategies (e.g., `ASYNC`) return a `message_id`. Incorrectly handling these return types is a common pitfall.
fix
Always check the documentation for the specific connection strategy you are using to understand its return values. For `ASYNC`, you typically need to call `get_response()` separately to retrieve the operation result. For multi-threaded programs, use `SAFE_SYNC` or `SAFE_RESTARTABLE`.
affects: All
gotchaSpecial characters in user-provided input for LDAP queries (e.g., `*`, `(`, `)`, `\`, NUL) must be properly escaped to prevent syntax errors and security vulnerabilities (like LDAP injection).
fix
Always escape user inputs before using them in LDAP filters or DNs. `ldap3` provides utility functions for this (e.g., `ldap3.utils.conv.escape_filter_chars`, `ldap3.utils.conv.escape_rdn_chars`). Never directly concatenate unescaped user input into LDAP queries.
affects: All
gotchaWhen using `ldap3` with `pyasn1` versions greater than `0.6.0`, a `DeprecationWarning` regarding `typeMap` vs. `TYPE_MAP` may be triggered. While typically harmless, it can clutter logs. This issue has been addressed in PR #983.
fix
Check for `ldap3` updates that include the fix for `pyasn1` compatibility. If warning persists and is disruptive, you may need to filter the warning or consider pinning `pyasn1 < 0.6.0` if feasible for your project, though this is not generally recommended for security/maintenance reasons.
affects: All `ldap3` versions with `pyasn1 > 0.6.0` (until `ldap3` officially incorporates the fix in a release, or you use a `bleeding-edge` version).
gotchaAttempting to connect to an LDAP server that is unreachable, not running, or blocking connections will result in an `LDAPSocketOpenError` (e.g., `Errno 111: Connection refused`). This indicates a network or server-side issue, not typically a library bug.
fix
Ensure the target LDAP server is running, accessible from the client machine, and listening on the specified host and port. Check network connectivity, firewall rules, and the LDAP server's configuration (e.g., `slapd.conf` or equivalent).
affects: All
gotchaWhen attempting to install `ldap3` with certain optional dependencies specified as extras (e.g., `ldap3[gssapi]`, `ldap3[winkerberos]`), `pip` may issue a warning that the specific extra is not provided by the installed `ldap3` version (e.g., 'ldap3 2.9.1 does not provide the extra 'gssapi''). This indicates that the requested optional dependency mechanism is not available or has changed for the specified extra, potentially leading to missing functionality.
fix
Consult the `ldap3` documentation for the correct way to install optional dependencies and available extras for your specific version. If an extra is not provided, you may need to install the underlying dependency (e.g., `python-gssapi` for GSSAPI support) separately and manually.
affects: >= 2.9.1
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'ldap3'
The `ldap3` library is not installed in the Python environment being used, or the Python interpreter cannot find it.
fix
Ensure `ldap3` is installed using pip: `pip install ldap3`. If using virtual environments, ensure the environment is activated. If encountering issues with `ldap` vs `ldap3`, ensure you are importing `ldap3` specifically if that is the intended library.
ldap3.core.exceptions.LDAPSocketOpenError: ('socket connection error while opening: [Errno 110] Connection timed out'
The Python client was unable to establish a network connection to the specified LDAP server, often due to the server being unreachable, incorrect IP/port, or firewall issues.
fix
Verify the LDAP server's IP address and port are correct and reachable from the client machine. Check firewall rules on both the client and server, and ensure the LDAP service is running on the server.
{'result': 49, 'description': 'invalidCredentials', ...}
The username, password, or Distinguished Name (DN) provided for the bind operation is incorrect or does not have the necessary permissions on the LDAP server.
fix
Double-check the username (often a full DN or a specific format like `domain\user` for Active Directory), password, and the `bind_dn` or `user` parameter in the `Connection` object. Ensure the account has the appropriate access rights for the requested operations.
ldap.INVALID_DN_SYNTAX: {'desc': 'Invalid DN syntax', ...}
A Distinguished Name (DN) provided in an LDAP operation (e.g., bind, add, modify) is not formatted according to LDAP syntax rules.
fix
Review the DN string for any typographical errors, incorrect escaping of special characters, or improper ordering of RDNs (Relative Distinguished Names). Ensure that all components (e.g., `CN=`, `OU=`, `DC=`) are correctly specified.
AttributeError: module 'ldap3' has no attribute 'POOLING_STRATEGY_FIRST'
This usually indicates that a constant or attribute is being accessed from the `ldap3` module directly, but it either does not exist, has been moved, or its name has changed in the version of `ldap3` being used. This specific error often relates to older versions or changes in the library's API for connection strategies.
fix
Consult the `ldap3` documentation for the specific version installed to find the correct attribute name or the updated way to implement the desired functionality. For connection strategies, import constants like `STRATEGY_SYNC`, `STRATEGY_ASYNC`, `STRATEGY_RESTARTABLE`, or `STRATEGY_THREADED` directly from `ldap3.core.connection`.
Upgrade
Version history
2.9.1latest on PyPI · released Jul 18, 2021
Audit
Dependencies
pyasn1requiredRequired for ASN.1 encoding/decoding, used for network communication.
pycryptodomexrequiredRequired for cryptographic operations, often used with SASL authentication.
gssapioptionalOptional, required for Kerberos SASL authentication.
winkerberosoptionalOptional, required for Kerberos SASL authentication on Windows clients.
Agent activity
11 hits · last 30 days
node
8
Amazon
1
OpenAI (training)
1
Resources
ldap3 — pip install ldap3 · libregistry