Connect with Python LDAP library
I wrote some python code using the python-ldap project, which wraps the openLDAP client, so ensure you have those two installed before looking at the Python code below.
# I use a Mac, so brew it is
brew install openldap
pip install python-ldap
Then fire up your favorite editor and write a few lines of code to anonymously bind and look up a user. You can look up a user by email using the email=*
query or by name using cn=*
.
import ldap
ldap_uri = 'ldap://server.example.com'
ldap_base = 'ou=server,o=example.com'
#query = "(cn=Steve Martinelli)"
query = "(email=stevemar@example.com)"
conn = ldap.initialize(ldap_uri)
result = conn.search_s(ldap_base, ldap.SCOPE_SUBTREE, query)
print(result)
You’ll get back something like this:
{
"ou": ["server"],
"o": ["example.com"],
"co": ["Canada"],
"emailAddress": ["stevemar@example.com"],
"cn": ["Steve Martinelli"]
}
What I like about the python-ldap library is that it makes things simple. Even after working for years on OpenStack’s Identity service I still scratch my head if given too many prompts.
Hope this helps others looking to whip up a quick prototype or two!
UPDATE: How to authenticate
I’ve had a few requests about why folks can’t authenticate to our LDAP with pyldap. It was the same problem every time. Folks were trying to authenticate with their email address instead of the full DN. Here’s some sample code with comments to show how to authenticate.
import ldap
ldap_uri = 'ldap://server.example.com'
ldap_base = 'ou=server,o=example.com'
conn = ldap.initialize(ldap_uri)
# Assume you get an email address and password as input...
user_email = 'stevemar@example.com'
pw = "mypassword"
# Look up the email in LDAP
query_email = "(email=" + user_email + ")"
# result[0][0] returns a full DN
# i.e. "uid=0123456789,c=ca,ou=server,o=example.com"
result = conn.search_s(ldap_base, ldap.SCOPE_SUBTREE, query_email)
user_dn = result[0][0]
print(user_dn)
# To authenticate the user you have to authenticate with the full DN
conn.simple_bind_s(user_dn, pw)