python - python中的LDAP查询

标签 python ldap ldap-query

我想在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

并使用由此获得的变量。我该怎么做?

最佳答案

虽然接受的答案实际上确实显示了绑定(bind)到 LDAP 服务器的正确方法,但我确实觉得它并没有从整体上回答这个问题。这是我最终实现以获取用户的邮件和部门的内容。这在某种程度上融合了原始问题的必需属性。

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()

关于python - python中的LDAP查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4784775/

相关文章:

python - Keras VGG 模型中 preprocess_input() 函数的作用是什么?

python - 在字典列表中搜索 Python 字典值的最佳方法是什么?

ldap - Openldap:是否可以使用 "userPassword"而不是 "2.5.4.35"作为 pwdAttribute?

php - 如何从 for 更改为 foreach

Java -> LDAP帐号密码加密

asp-classic - 如何格式化包含特殊字符的 LDAP 过滤器? ('Classic' ASP)

python - Python 中的 is 运算符

c# - 尝试解析跨存储引用时,无法解析目标主体的 SID。错误代码为 1332

ldap - 在搜索过滤器中使用 DN

python - numpy 的内存错误在哪里