Recipe 13.17. Accessing LDAP Servers
Credit: John Nielsen
Problem
You need to
access an LDAP (Lightweight Directory Access Protocol) server from
your Python programs.
Solution
The simplest solution is offered by the freely downloadable
third-party extension ldap (http://python-ldap.sourceforge.net). This
script shows a few LDAP operations with
ldap:
try:
path = 'cn=people,ou=office,o=company'
l = ldap.open('hostname')
# set which protocol to use, if you do not like the default
l.protocol_version = ldap.VERSION2
l.simple_bind('cn=root,ou=office,o=company','password')
# search for surnames beginning with a
# available options for how deep a search you want:
# LDAP_SCOPE_BASE, LDAP_SCOPE_ONELEVEL,LDAP_SCOPE_SUBTREE,
a = l.search_s(path, ldap.SCOPE_SUBTREE, 'sn='+'a*')
# delete fred
l.delete_s('cn=fred,'+path)
# add barney
# note: objectclass depends on the LDAP server
user_info = {'uid':'barney123',
'givenname':'Barney',
'cn':'barney123',
'sn':'Smith',
'telephonenumber':'123-4567',
'facsimiletelephonenumber':'987-6543',
'objectclass':('Remote-Address','person', 'Top'),
'physicaldeliveryofficename':'Services',
'mail':'fred123@company.com',
'title':'programmer',
}
id = 'cn=barney,'+path
l.add_s(id, user_info.items( ))
except ldap.LDAPError, error:
print 'problem with ldap:', error
Discussion
The
ldap module wraps the open source Openldap C API.
However, with ldap, your Python program can talk
to various versions of LDAP servers, as long as
they're standards compliant, not just to Openldap
servers.The recipe shows a script with a few example uses of the
ldap module. For simplicity, all the functions the
recipe calls from the library are the '_s'
versions (e.g., search_s): this means the
functions are synchronousthat is, they wait for a response or
an error code and don't return control to your
program until either an error or a response appears from the server.
Asynchronous programming is less elementary than synchronous,
although it can often offer far better performance and scalability.LDAP is widely used to keep and coordinate network-accessible
information, particularly in large and geographically distributed
organizations. Essentially, LDAP lets you organize information,
search for it, create new items, and delete existing items. The
ldap module lets your Python program perform the
search, creation, and deletion functions.
See Also
http://python-ldap.sourceforge.net/docs.shtml
for all the documentation about the ldap module
and other relevant pointers.