python中的LDAP查询

时间:2011-01-24 17:04:23

标签: 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

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

4 个答案:

答案 0 :(得分:37)

虽然接受的答案确实显示了绑定到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()

答案 1 :(得分:9)

您可能想要"ldap"模块。代码看起来像:

    import ldap
    l = ldap.initialize('ldap://ldapserver')
    username = "uid=%s,ou=People,dc=mydotcom,dc=com" % username
    password = "my password"
    try:
      l.protocol_version = ldap.VERSION3
      l.simple_bind_s(username, password)
      valid = True
    except Exception, error:
      print error

答案 2 :(得分:2)

这是python-ldap的示例生成器。

ldap_server是您从ldap.initialize()获得的对象。在调用此函数之前,您可能还需要绑定,具体取决于您使用的LDAP服务器以及您要查询的内容。 base_dnfilter_类似于您在命令行版本中获得的内容。 limit是返回的最大记录数。

def _ldap_list(ldap_server, base_dn, filter_, limit=0):
    """ Generator: get a list of search results from LDAP asynchronously. """

    ldap_attributes = ["*"] # List of attributes that you want to fetch.
    result_id = ldap_server.search(base_dn, ldap.SCOPE_SUBTREE, filter_, ldap_attributes)
    records = 0

    while 1:
        records += 1

        if limit != 0 and records > limit:
            break

        try:
            result_type, result_data = ldap_server.result(result_id, 0)
        except ldap.NO_SUCH_OBJECT:
            raise DirectoryError("Distinguished name (%s) does not exist." % base_dn)

        if result_type == ldap.RES_SEARCH_ENTRY:
            dn = result_data[0][0]
            data = result_data[0][1]
            yield dn, data
        else:
            break

请记住,将用户提供的值插入LDAP查询是危险的!这是一种允许恶意用户更改查询含义的注入形式。请参阅:http://www.python-ldap.org/doc/html/ldap-filter.html

答案 3 :(得分:0)

您可以使用命令模块和getoutput来解析ldap查询的结果:

from commands import getoutput
result = getoutput('ldapsearch -h hostname -b dc=ernet,dc=in -x "(&(uid=w2lame)(objectClass=posixAccount))"')
print result

你必须在系统中安装ldapsearch二进制文件。

问候.-