【问题标题】:LDAP Query in Python3Python3中的LDAP查询
【发布时间】:2021-02-22 14:56:34
【问题描述】:

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

谢谢

【问题讨论】:

  • 我不知道这是否是一个错字,但看起来变量searchScope 没有在您的代码中定义,如果您将范围设置为l.search_s(basedn, ldap.SCOPE_SUBTREE, ...) 会发生什么?
  • @EricLavault,抱歉打错了。我更新了。

标签: python-3.x ldap ldap-query python-ldap ldap3


【解决方案1】:

事实证明,我没有在代码中使用 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"))

【讨论】:

  • 这似乎是一种不必要的复杂处理方式。为什么是简单的json?如果 search_s 本身已经返回结果,为什么还要搜索+结果?
  • @user1686 当我使用 search_s 时,脚本会冻结而不是终止并提供输出。
  • @user1686 嘿,谢谢。我做了一些挖掘,发现 search_s 确实发送了一些引荐,LDAP 自动在内部使用匿名访问来追踪引荐,但失败了。所以添加 ``` connection.set_option(ldap.OPT_REFERRALS, 0)``` 与 search_s 完美配合
猜你喜欢
  • 2017-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-24
  • 2020-05-18
相关资源
最近更新 更多