A little python-ldap tutorial

LDAP Search

One day we decided to change our own-written C++ app for interaction with LDAP. Of course, we choose python-ldap (python-ldap site).

But it wasn’t so simple, as I thought, and docs are not very simple, I can’t find any acceptable tutorial and spend some time at StackOverflow. After that I decided to write this little tutorial.

First, we need to import our module

import ldap

Then, initialize our connect to ldap-server

connect = ldap.initialize('ldap://our-ldap.server')

Then we need to use our credentials to search LDAP

connect.set_option(ldap.OPT_REFERRALS, 0)

And bind our server

connect.simple_bind_s('ldap_login', 'ldap_password')

Here you need to insert your login and password instead of ldap_login and ldap_password.

That’s it! Now we can search in ldap whatever we want!

And a little tip about why simple_bind_s — ‘_s’ at the end mean that this request will be executed synchronously. Without that all requests are called asynchronously.

Here is an example for user search

result = connect.search_s('dc=somedomain,dc=com',

In that example we search in which groups is our user.

dc=somedomain,dc=com’ — our domain

ldap.SCOPE_SUBTREE — to search the object and all its descendants

userPrincipalName=user@somedomain.com’ — search method of out user (instead of userPrincipalName we can use displayName (and instead of user@somedomain.com — User User, for example), because it unique too)

[‘memberOf’] — attributes, that we want to receive. If we will not fill this part — we will receive all user ldap-attributes.

The result is a list of tuples. Tuple consist of full domain name and dict with attributes as keys, and values is lists.

In our case

[(‘CN=user,OU=user_orgunit,OU=Users,OU=City,DC=somedomain,DC=com’, {‘memberOf’: [‘group1’, ‘group2’]})]

In this manner we can search not only users, but also all domain objects.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.