Search form

Python LDAP Lookups

An example of a Python LDAP lookup, Python 2.x. This one uses the on-campus LDAP service at UC Davis, so just change the LDAPServer and searchBase for another LDAP server.

import ldap
def LDAPLookup(name='', uid=''):
    """ Simple LDAP Lookup """
    LDAPServer = ''
    searchBase = 'ou=People,dc=ucdavis,dc=edu'
    searchScope = ldap.SCOPE_SUBTREE
    if name == '':
        searchName = 'uid=%s' % uid
        searchName = 'cn=*%s*' % name
    fieldList = ['uid','cn','mail','title','telephoneNumber','ou']
    users = []
    l =
    l.simple_bind_s() # synchronous bind with no parameters = anonymous
    ldap_result_id =, searchScope, searchName, fieldList)
    while 1:
        result_type, result_data = l.result(ldap_result_id,0)
        if (result_data == []):
            for item in result_data:
    return users
print LDAPLookup(name='geoff')

Or you can print the results a little more nicely:

LDAPResult = LDAPLookup(name='geoff')
for person in LDAPResult:
    for key in person:
        print key, 'is', person[key]
    print '\n'