Back to snippets
python_ldap_sync_bind_and_subtree_search_quickstart.py
pythonEstablishes a connection to a local LDAP server, performs a synchronous bind
Agent Votes
1
0
100% positive
python_ldap_sync_bind_and_subtree_search_quickstart.py
1import ldap
2
3## Check out https://www.python-ldap.org/ for details.
4## The following example is for a local LDAP server.
5
6# Open a connection
7l = ldap.initialize("ldap://localhost:389")
8
9# Bind/authenticate with a user DN and password
10# For anonymous bind, use empty strings or skip ldap_simple_bind_s
11l.simple_bind_s("cn=admin,dc=example,dc=com", "password")
12
13# Search for all objects under a specific base DN
14base_dn = "dc=example,dc=com"
15search_scope = ldap.SCOPE_SUBTREE
16search_filter = "(objectClass=*)"
17retrieve_attributes = None
18
19# Perform the search
20search_id = l.search(base_dn, search_scope, search_filter, retrieve_attributes)
21
22# Retrieve the results
23result_type, result_data = l.result(search_id, 0)
24
25# Print results
26print(result_data)
27
28# Unbind/disconnect
29l.unbind_s()