None

Adding Users to LDAP and Querying

December 26, 2009

This entry covers adding users to the Apache Directory LDAP server and using python-ldap to compare values against the respository.

Adding Users

Assuming that you have added the domain (drumcoder.co.uk) as specified in Adding a domain to Apache LDAP, we now need to add users to it.

Right click dc=drumcoder,dc=co,dc=uk and select New Entry. Create an entry from scratch and click Next. On this screen you enter the type of data you want to store about each user. For now, select uidObject and inetOrgPerson. Click next. For the RDN select uid, and set the value dcuser. Click next. This will prompt for all required fields. Fill in a cn of Drum Coder and a sn of Coder. (Right click to get the Edit Attribute option for each field). Click finish.

LDAP Compare with Python

We're now going to write some simple code to check if the sn of a user is as specified. First we start with setting up the repository and binding to it:

import ldap
>>> con = ldap.initialize('ldap://localhost:10389')
>>> dn = "uid=admin,ou=system"
>>> password = "secret"
>>> con.simple_bind_s(dn,password)
(97, [])

Next, we use the compare function to see if the sn value is Coder for uid=dcuser.

>>> dn = 'uid=dcuser,dc=drumcoder,dc=co,dc=uk'
>>> con.compare_s(dn, 'sn' ,'Coder')
1
>>> con.compare_s(dn, 'sn' ,'Not Coder')
0

As you can see, this is checking the repository to compare the sn string with the value specified, and it returns 1 for success, and 0 for failure.

Searching

You can search for LDAP entries matching search criteria. Here's a search for all of the entries of class peron, below drumcoder.co.uk. It will return all of the entries that match the search criteria, complete with the attributes specified:

>>> base_dn = 'dc=drumcoder,dc=co,dc=uk'
>>> filter = '(objectclass=person)'
>>> attrs = ['sn','uid']
>>> con.search_s(base_dn, ldap.SCOPE_SUBTREE, filter, attrs)
[('uid=dcuser,dc=drumcoder,dc=co,dc=uk', {'uid': ['dcuser'], 'sn': ['Coder']}),    
('uid=dcuser2,dc=drumcoder,dc=co,dc=uk', {'uid': ['dcuser2'], 'sn': ['Second Coder']})]

Note that I added a second user through Apache Directory Studio in order to test this. Changing the value of the sn for a particular user will be immediately available if you run the search again.