LDAP Programming in Python
You've heard about the next generation directory protocol called LDAP (lightweight directory access protocol), and you're wondering if it's possible to write programs that can interact with it. Maybe you've even set up an LDAP server of your own, and now you want to write programs for it. To these ends, this article gets you ready to write your own programs to automate the querying process of LDAP servers. Hopefully, it also provides you with a solid foundation for extending your knowledge to write configuration scripts and whatever else you want to do with LDAP.
Most major programming languages have an LDAP API, but I chose to use Python because it is perhaps the easiest and clearest language with which to demonstrate. If you do not already understand the basics of the Python programming language and LDAP, you probably should come back to this tutorial after you have become better acquainted with them.
Writing programs that access LDAP servers is easy to do using Python and python-ldap. The python-ldap package contains a module that wraps the OpenLDAP C API and provides an object-oriented client API to interact with LDAP directory servers. The package also contains modules to do other tasks related to LDAP, such as processing LDIF, LDAPURLs and LDAPv3 schemes and more.
Currently, standard implementations of Python do not come with python-ldap, but you can download it as a third-party package from SourceForge.
The best way to learn is to write an example program, so let's write a small and complete program to fetch some specific contact information from an LDAP server. Because indentation matters in Python, all the code given below is indented, so copy it as you see it.
The first thing we need to do is import the ldap module. So open your favorite text editor and type import ldap. For this program, we need to create two simple functions:
a main() function that binds the program to an LDAP server and calls a search function
a function called my_search() that is used to retrieve/display data from the server.
Let's create our main function and set up variables to authenticate with the LDAP server by using def main():.
If you are using a public server, you can leave the values for the who and cred blank. You can get a list of some public LDAP servers here
. It looks something like this:
server = "ldap.somewhere.edu"
who = ""
cred = ""
Now we need to make a keyword set to what we want our search string to be. I use my first name for this sample program:
keyword = "ryan"
Next, we need to bind to the LDAP server. Doing so creates an object named "l" that is then used throughout the program.
try:
l = ldap.open(server)
l.simple_bind_s(who, cred)
print "Successfully bound to server.\n"
We're now ready to query the server. We also now catch any possible errors if there is a problem authenticating:
print "Searching..\n"
my_search(l, keyword)
except ldap.LDAPError, error_message:
print "Couldn't Connect. %s " % error_message
Having written our main function, we now can create our search function:
def my_search(l, keyword):
In a moment we will be calling python-ldap's built-in search method on our l object. Four variables--base, scope, filter and retrieve_attributes--are the parameters of that search method. Base is used for the DN (distinguished name) of the entry where the search should start. You can leave it blank for this example:
base = ""
For scope we use SCOPE_SUBTREE to search the object and all its descendants:
scope = ldap.SCOPE_SUBTREE
Our search filter consists of a cn (common name) and our keyword. Putting asterisks around our keyword (ryan) will match anything with the string ryan, such as Bryant.
filter = "cn=" + "*" + keyword + "*"
The last argument we pass to the search method is used to return all the attributes of each entry:
retrieve_attributes = None
Now, let's setup a few more variables, including a counter to keep track of the number of results returned:
count = 0
a list to append the results to:
result_set = []
and a variable to specify the length, in seconds, we're willing to wait for a response from the server:
timeout = 0
Now we can begin our search by calling python-ldap's search method on our l object:
try:
result_id = l.search(base, scope, filter, retrieve_attributes)
Store any results in the result_set list
while 1:
result_type, result_data = l.result(result_id, timeout)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
If we were to print result_set now, it might look like a big list of tuples and dicts. Instead, step through it and select only the data we want to see
if len(result_set) == 0:
print "No Results."
return
for i in range(len(result_set)):
for entry in result_set[i]:
try:
name = entry[1]['cn'][0]
email = entry[1]['mail'][0]
phone = entry[1]['telephonenumber'][0]
desc = entry[1]['description'][0]
count = count + 1
Display the data, if any was found, in the following format:
1. Name: Description: E-mail: Phone: 2. Name: Description: E-mail: Phone: etc..
print "%d.\nName: %s\nDescription: %s\nE-mail: %s\nPhone: %s\n" %\
(count, name, desc, email, phone)
except:
pass
except ldap.LDAPError, error_message:
print error_message
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- What's the tweeting protocol?
- New Products
- RSS Feeds
- Readers' Choice Awards
- Dart: a New Web Programming Experience
- Reply to comment | Linux Journal
12 hours 53 min ago - Reply to comment | Linux Journal
15 hours 25 min ago - Reply to comment | Linux Journal
16 hours 42 min ago - great post
17 hours 17 min ago - Google Docs
17 hours 40 min ago - Reply to comment | Linux Journal
22 hours 28 min ago - Reply to comment | Linux Journal
23 hours 15 min ago - Web Hosting IQ
1 day 49 min ago - Thanks for taking the time to
1 day 2 hours ago - Linux is good
1 day 4 hours ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.



Comments
thanks very much, I tried
thanks very much, I tried your code, it works well. But when I learn it from someother ldap server, i found that i cann't use the base="", I must write the concrete base if i want it to work. I really want to know what is the problem. I googled for this question, failed to get the reson, could you help me. I am really confused about this: why you said, in this example: base can be "". fortunately, the first example I tried with "" is also ok. I am a fresh bird, can someone help me?? That will be very appreciated.
I have just start to learn python
thanks for your share. i will have a try and learn.
I tried python for the first
I tried python for the first time and noticed that tabbing cripples the whole python language. Thanks and goodbye
Translation
Great!
Thanks.
We have translated your article in russian. If you have no objection - posted it on our website.
http://www.komtet.ru/info/python/ldap-v-python
Quite poorly written. The
Quite poorly written. The following is a much more practical explanation of getting started with python & ldap.
http://www.grotan.com/ldap/python-ldap-samples.html
It was good for the time
Keep in mind that in 2003, when this article was written, there were no other articles on LDAP programming in Python. So I think it was quite good for the time.
By the way, the linked code
By the way, the linked code is terrible. It's like someone tried to adapt another language for python.
The search code uses a permanent TRUE statement with a break.
Bad code
I was able to pick out the basics from this example, but the python code is terrible...
Re: LDAP Programming in Python
The code, for the most part, works for me. But I'm having trouble slicing the data portions out of the search result.
When grabbing 'description' (or any other attribute), I'm getting back:
string indices must be integers " entry[1]['description'][0] "
Re: LDAP Programming in Python
try this:
entyr[0][1]['description']
look for Python's Manual about List, Tuple and Dictionary!