I want to execute the following query in the ldap
ldapsearch -h hostname -b dc=ernet,dc=in -x "(&(uid=w2lame)(objectClass=posixAccount))" gidnumber ldapsearch -h hostname -b dc=ernet,dc=in -x "(&(gidNumber=1234)(objectClass=posixGroup))" cn
And use the variables thus obtained. How can I do that?
The easiest way to search LDAP is to use ldapsearch with the “-x” option for simple authentication and specify the search base with “-b”. If you are not running the search directly on the LDAP server, you will have to specify the host with the “-H” option.
In order to use LDAP with Python we need to import the Server and the Connection object, and any additional constant we will use in our LDAP. As you might remember from the LDAP Protocol diagram the authentication operation is called Bind.
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 UserUnits searchScope = ldap.SCOPE_SUBTREE #Bind to the server try: 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_set except ldap.LDAPError, e: print e l.unbind_s()
You probably want to use the ldap
module. Code would look something like:
import ldap l = ldap.initialize('ldap://ldapserver') username = "uid=%s,ou=People,dc=mydotcom,dc=com" % username password = "my password" try: l.protocol_version = ldap.VERSION3 l.simple_bind_s(username, password) valid = True except Exception, error: print error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With