Problem

I’m working on a side project in django, and I wanted to extend its functionality by tying into my company’s ActiveDirectory. I included python-ldap in my project and started probing for the functionality I wanted. After getting the initialization and binding out of the way, I decided to try searching for my user:

import ldap

con = ldap.initialize('ldap://example.com')

ldap_user = 'ldapdev@example.com'
passwd = 'passwd'
base_dn = 'DC=example,DC=com'

con.simple_bind_s(ldap_user, passwd)
filter_str = "samaccountname=chaverma"
attrs = ('samaccountname', 'displayname', 'department')
con.search_s(base_dn, ldap.SCOPE_SUBTREE, filterstr=filter_str, attrlist=attrs)

This script hangs interminably in my environment. I tried activating traces and debug information and didn’t get much further. I found that my data did return but the interpreter became unresponsive.

Solution

Research on this particular symptom returned nothing. Eventually I tried doing what was suggested in this Stacko question and I immediately got better results:

>>> import ldap

>>> ldap.set_option(ldap.OPT_REFERRALS, 0)
>>> con = ldap.initialize('ldap://example.com')

>>> ldap_user = 'ldapdev@example.com'
>>> passwd = 'passwd'
>>> base_dn = 'DC=example,DC=com'

>>> con.simple_bind_s(ldap_user, passwd)
>>> filter_str = "samaccountname=chaverma"
>>> attrs = ('samaccountname', 'displayname', 'department')
>>> con.search_s(base_dn, ldap.SCOPE_SUBTREE, filterstr=filter_str, attrlist=attrs)
[('CN=Christopher Haverman,OU=Engineering Corp, <snip>...')]
>>> 

Problem solved! The takeaway is that if you’re working in python-ldap, you need to set this option to get the desired behavior.