LDAP query in python LDAP query in python python python

LDAP query in python


While the accepted answer does in fact show a proper way to bind to an LDAP server I do feel it didn't answer the question holistically. Here is what I ended up implementing to grab the mail and department of a user. This somewhat blends the required attributes from the original question.

l = ldap.initialize('ldap://ldap.myserver.com:389')binddn = "cn=myUserName,ou=GenericID,dc=my,dc=company,dc=com"pw = "myPassword"basedn = "ou=UserUnits,dc=my,dc=company,dc=com"searchFilter = "(&(gidNumber=123456)(objectClass=posixAccount))"searchAttribute = ["mail","department"]#this will scope the entire subtree under UserUnitssearchScope = ldap.SCOPE_SUBTREE#Bind to the servertry:    l.protocol_version = ldap.VERSION3    l.simple_bind_s(binddn, pw) except ldap.INVALID_CREDENTIALS:  print "Your username or password is incorrect."  sys.exit(0)except ldap.LDAPError, e:  if type(e.message) == dict and e.message.has_key('desc'):      print e.message['desc']  else:       print e  sys.exit(0)try:        ldap_result_id = l.search(basedn, searchScope, searchFilter, searchAttribute)    result_set = []    while 1:        result_type, result_data = l.result(ldap_result_id, 0)        if (result_data == []):            break        else:            ## if you are expecting multiple results you can append them            ## otherwise you can just wait until the initial result and break out            if result_type == ldap.RES_SEARCH_ENTRY:                result_set.append(result_data)    print result_setexcept ldap.LDAPError, e:    print el.unbind_s()


You probably want to use the ldap module. Code would look something like:

import ldapl = ldap.initialize('ldap://ldapserver')username = "uid=%s,ou=People,dc=mydotcom,dc=com" % usernamepassword = "my password"try:    l.protocol_version = ldap.VERSION3    l.simple_bind_s(username, password)    valid = Trueexcept Exception, error:    print error


Here's an example generator for python-ldap.

The ldap_server is the object you get from ldap.initialize(). You will probably need to bind before calling this function, too, depending on what LDAP server you are using and what you are trying to query for. The base_dn and filter_ are similar to what you've got in your command line version. The limit is the maximum number of records returned.

def _ldap_list(ldap_server, base_dn, filter_, limit=0):    """ Generator: get a list of search results from LDAP asynchronously. """    ldap_attributes = ["*"] # List of attributes that you want to fetch.    result_id = ldap_server.search(base_dn, ldap.SCOPE_SUBTREE, filter_, ldap_attributes)    records = 0    while 1:        records += 1        if limit != 0 and records > limit:            break        try:            result_type, result_data = ldap_server.result(result_id, 0)        except ldap.NO_SUCH_OBJECT:            raise DirectoryError("Distinguished name (%s) does not exist." % base_dn)        if result_type == ldap.RES_SEARCH_ENTRY:            dn = result_data[0][0]            data = result_data[0][1]            yield dn, data        else:            break

Please keep in mind that interpolating user-provided values into your LDAP query is dangerous! It's a form of injection that allows a malicious user to change the meaning of the query. See: http://www.python-ldap.org/doc/html/ldap-filter.html