LDAP uid路径未知

时间:2016-03-29 13:50:12

标签: python ldap bind

这里有我工作的python脚本:

#!/usr/bin/python

import ldap, sys

l = ldap.initialize('ldap://myldapserver:389')
username = "uid=%s,OU=folder1,OU=myCompany,O=MyCompanyGroup" % "myID"
password = "mypassword"
try:
  l.protocol_version = ldap.VERSION3
  l.simple_bind_s(username, password)
  valid = True
  print "OK"
  l.unbind()
except Exception, error:
  print error

现在我想绑定用户,只是指定" O = MyCompanyGroup",并在该子树上搜索uid。例如,我可以根据" inetOrgPerson "

进行过滤

我试过

 username = "(&(objectClass=inetOrgPerson )(uid=%s)(O=MyCompanyGroup))" % "myID"

但我获得了无效的凭据。

谢谢! 的Riccardo

2 个答案:

答案 0 :(得分:0)

找到解决方案

#!/usr/bin/python

import ldap, sys

l = ldap.initialize('ldap://myldapserver:389')
search_filter = "(&(uid=myID)(objectClass=inetOrgPerson))"
base_dn="O=MyCompanyGroup"
password = "mypassword"
try:
  l.protocol_version = ldap.VERSION3
  result = l.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter, None)
  user_dn = result[0][0]
  print user_dn
  l.simple_bind_s(user_dn, password)
  valid = True
  print "OK"
  l.unbind()
except Exception, error:
  print error

答案 1 :(得分:0)

好的技术@ Riccardo79

在我的情况下,我被迫首先以LDAP管理员身份登录以执行用户密码检查。

这是我的代码:

import ldap

ldap_admin_dn = "cn=admin..."
ldap_admin_password = "..."
ldap_users_dn="ou=to,ou=my,ou=users..."

def connectLDAP(self, username, password) -> bool:
    search_filter = "(&(uid={})(objectClass=inetOrgPerson))".format(username)
    try:
        connection = ldap.initialize(self.ldap_endpoint)
        connection.protocol_version = ldap.VERSION3
        connection.simple_bind_s(ldap_admin_dn, ldap_admin_password)
        result = connection.search_s(ldap_users_dn, ldap.SCOPE_SUBTREE, search_filter)
        user_dn = result[0][0]
        connection.simple_bind_s(user_dn, password)
        connection.unbind()
    except ldap.LDAPError as e:
        print(e)
        return False
    return result