我有一个LDAP查询,它在我的终端上运行得很好
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
我想在python3中运行这个命令,我遵循StackOverflow的其他答案并写了这样的东西,
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()
但是这里我没有得到ldap_result_id的结果。有人能帮助什么是正确的方式来做这个查询吗?
感谢事实证明,我没有在代码中使用connection.set_option(ldap.OPT_REFERRALS, 0)
,并且在LDAP中存在一些问题,该问题自动在内部追踪匿名访问失败的引用。
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"))