Of course. Let's break down what "python ldap 2.4.27" means, how to work with it, and where to find the crucial documentation.

What is python-ldap 2.4.27?
python-ldap is a mature and widely-used library for Python that provides object-oriented access to LDAP (Lightweight Directory Access Protocol) directory servers. It's not part of Python's standard library, so you need to install it separately.
The version number 4.27 refers to a specific release of this library.
- Major Version (2): Indicates a significant change in the API. While
python-ldaphas been stable for a long time, a major version bump could introduce breaking changes. - Minor Version (4): Typically indicates new features or significant enhancements that are backward-compatible.
- Patch Version (27): Indicates bug fixes and minor improvements. This is a high patch number, suggesting it's a mature and stable release within the 2.4 series.
Important Note: The python-ldap library is a Python wrapper around the OpenLDAP C library. This means you must have the OpenLDAP development libraries installed on your system before you can install python-ldap via pip.
Installation
Before you install python-ldap, ensure your system has the necessary dependencies.
A. Install System Dependencies
On Debian/Ubuntu:
sudo apt-get update sudo apt-get install python3-dev libldap2-dev libsasl2-dev
python3-dev: Provides the Python headers needed to compile C extensions.libldap2-dev: The OpenLDAP C library development files.libsasl2-dev: The SASL (Simple Authentication and Security Layer) library, used for authentication.
On Red Hat/CentOS/Fedora:
sudo yum install python3-devel openldap-devel cyrus-sasl-devel # Or for dnf sudo dnf install python3-devel openldap-devel cyrus-sasl-devel
On macOS (using Homebrew):
brew install openldap # You may also need to set the environment variables for the linker export LDFLAGS="-L$(brew --prefix openldap)/lib" export CPPFLAGS="-I$(brew --prefix openldap)/include"
B. Install python-ldap via pip
Once the system dependencies are in place, you can install the library. You can install the specific version 4.27 or the latest version.
# Install a specific version (2.4.27) pip install python-ldap==2.4.27 # Or install the latest version of the 2.4.x series pip install "python-ldap>=2.4.27,<2.5.0" # Or simply install the latest version available pip install python-ldap
Basic Usage Examples
The library is powerful, so here are some common tasks to get you started. You'll need an LDAP server to connect to for these examples to work.
A. Connecting and Browsing (Anonymous Bind)
This example connects to an LDAP server and lists the entries at the base DN (Distinguished Name).
import ldap
# --- Configuration ---
# Replace with your LDAP server details
SERVER_URI = "ldap://ldap.example.com"
BASE_DN = "dc=example,dc=com"
try:
# 1. Initialize the LDAP object
# Use ldap.SSL for ldaps:// connections
l = ldap.initialize(SERVER_URI)
l.protocol_version = ldap.VERSION3
# 2. Perform an anonymous bind
# This is often allowed for reading public information
l.simple_bind_s("", "")
# 3. Define the search scope and filter
# scope=ldap.SCOPE_SUBTREE: Search the entire tree under BASE_DN
# filter: '(objectClass=*)' means "get all objects"
search_filter = "(objectClass=*)"
result = l.search_s(BASE_DN, ldap.SCOPE_SUBTREE, search_filter)
# 4. Print the results
print(f"Found {len(result)} entries:")
for dn, entry in result:
print(f" - DN: {dn}")
print(f" Attributes: {entry}\n")
except ldap.LDAPError as e:
print(f"An LDAP error occurred: {e}")
finally:
# 5. Unbind the connection
if 'l' in locals():
l.unbind()
B. Authenticating a User (Simple Bind)
This example binds to the LDAP server using a user's DN and password to authenticate them.
import ldap
# --- Configuration ---
SERVER_URI = "ldap://ldap.example.com"
USER_DN = "cn=john.doe,ou=users,dc=example,dc=com"
USER_PASSWORD = "secure_password"
try:
# 1. Initialize and set protocol version
l = ldap.initialize(SERVER_URI)
l.protocol_version = ldap.VERSION3
# 2. Perform the bind with the user's credentials
# simple_bind_s() will raise an exception if the bind fails
l.simple_bind_s(USER_DN, USER_PASSWORD)
print(f"Successfully authenticated user: {USER_DN}")
# You can now perform searches as this authenticated user
search_filter = "(uid=john.doe)"
user_info = l.search_s("ou=users,dc=example,dc=com", ldap.SCOPE_SUBTREE, search_filter)
print(f"User info: {user_info[0][1]}")
except ldap.INVALID_CREDENTIALS:
print("Error: Invalid username or password.")
except ldap.LDAPError as e:
print(f"An LDAP error occurred: {e}")
finally:
if 'l' in locals():
l.unbind()
C. Searching for a User
This example shows how to construct a more specific search filter to find a user by their uid.
import ldap
# --- Configuration ---
SERVER_URI = "ldap://ldap.example.com"
BASE_DN = "ou=users,dc=example,dc=com"
SEARCH_FILTER = "(uid=jane.doe)" # Use the user's unique identifier
ATTRIBUTES = ['cn', 'mail', 'telephoneNumber'] # Specific attributes to retrieve
try:
l = ldap.initialize(SERVER_URI)
l.protocol_version = ldap.VERSION3
# Anonymous bind is often sufficient for searches if permissions allow
l.simple_bind_s("", "")
# Perform the search
# The result is a list of tuples: [(dn, {'attr': ['value', ...]}), ...]
result = l.search_s(
base=BASE_DN,
scope=ldap.SCOPE_SUBTREE,
filterstr=SEARCH_FILTER,
attrlist=ATTRIBUTES
)
if not result:
print(f"No user found with uid: {SEARCH_FILTER[1:-1]}")
else:
dn, attributes = result[0]
print(f"Found User: {dn}")
for attr, values in attributes.items():
# Values are always returned as a list
print(f" {attr}: {', '.join(values)}")
except ldap.LDAPError as e:
print(f"An LDAP error occurred: {e}")
finally:
if 'l' in locals():
l.unbind()
Where to Find Documentation
The documentation for python-ldap is essential, as the library is a direct mapping of the C API concepts.
-
Official Documentation (The Best Resource):
- Homepage: https://www.python-ldap.org/
- Documentation: https://www.python-ldap.org/doc/html/
- API Reference: This is the most important link. It details every function, class, and constant. You can find it in the documentation sidebar or directly at the link above.
-
GitHub Repository:
- You can find the source code, issue tracker, and sometimes more detailed examples here.
- URL: https://github.com/python-ldap/python-ldap
-
PyPI Page:
- Useful for checking the latest version, dependencies, and user comments.
- URL: https://pypi.org/project/python-ldap/
Important Considerations
- Security: For production environments, always use
ldaps://(LDAP over SSL/TLS) orldap://with theSTARTTLSextension to encrypt your connections. Theinitialize()call would look likeldap.initialize("ldaps://your-server"). - Error Handling: The
ldap.LDAPErroris the base exception class. It's good practice to catch more specific exceptions likeldap.INVALID_CREDENTIALS,ldap.NO_SUCH_OBJECT,ldap.INSUFFICIENT_ACCESS, etc., to handle different failure scenarios gracefully. - Alternatives: For simpler use cases, consider libraries like
python-kerberosfor GSSAPI authentication or higher-level abstractions built on top ofpython-ldap. However, for direct and full control,python-ldapis the standard.
