首页 > 解决方案 > Python3中的LDAP查询

问题描述

我有一个 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 得到结果。任何人都可以帮助执行此查询的正确方法是什么?

谢谢

标签: python-3.xldapldap-querypython-ldapldap3

解决方案


事实证明,我没有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"))


推荐阅读