-1

I have an LDAP Query which is running perfectly fine in my terminal

ldapsearch -h ldap.mygreatcompany.com -D user@mygreatcompany.COM -w "$ldappassword" -b "DC=abc,DC=mygreatcompany,DC=com" -s sub "(mail=user1@mygreatcompany.COM)" sAMAccountName

I want to run this command in python3, I followed other answers from StackOverflow and wrote something like this,

import ldap
l = ldap.initialize('ldap://ldap.mygreatcompany.com')

binddn = "user@mygreatcompany.COM"
pw = #ldappassword
basedn = "DC=abc,DC=mygreatcompany,DC=com"
searchAttribute = ["sAMAccountName"]
searchFilter = "(&(mail=user1@mygreatcompany.COM')(objectClass=*))"
searchScope = ldap.SCOPE_SUBTREE

l.simple_bind_s(binddn, pw) 
ldap_result_id = l.search_s(basedn, searchScope, searchFilter, searchAttribute)

#Get result

l.unbind_s()

But Here I am not getting the result from ldap_result_id. Can anybody help what is the correct way to do this query?

Thanks

1 Answers1

0

It turns out that I was not using connection.set_option(ldap.OPT_REFERRALS, 0) in the code and there is some issue in LDAP which automatically chases the referrals internally with anonymous access which fails.

Here is the working code:

def get_user_id(email):
# Seach fiter for user mail
    searchFilter = "mail={}".format(email)

    try:
        # binding to ldap server
        connection = ldap.initialize('ldap://yourcompanyhost')
        connection.set_option(ldap.OPT_REFERRALS, 0)
        connection.protocol_version = ldap.VERSION3
        connection.simple_bind_s(binddn, pwd) 

        # get result
        ldap_result_id = connection.search_s(basedn, searchScope, searchFilter, searchAttribute)

        # extract the id
        saMAccount = ldap_result_id[0][1]["sAMAccountName"][0].decode('utf-8')

    except ldap.INVALID_CREDENTIALS:
        print("Your username or password is incorrect.")
    except ldap.LDAPError as e:
        print(e)
    except:
        print("Data doesn't exist for this user")
    connection.unbind_s()


print(get_user_id("user1@mygreatcompany.COM"))

  • That seems like an unnecessarily complex way of doing things. Why simplejson? Why search+result, if search_s already returns the result itself? – user1686 Feb 22 '21 at 21:49
  • @user1686 When I use search_s, the script is freezing and not terminating and giving output. – Kishan Kumar Gupta Feb 23 '21 at 06:26
  • @user1686 Hey thank you. I did some digging and found that search_s does send some referrals and LDAP automatically chases the referrals internally with anonymous access which fails. So adding ``` connection.set_option(ldap.OPT_REFERRALS, 0)``` worked perfectly with search_s – Kishan Kumar Gupta Feb 23 '21 at 17:15