使用Python进行LDAP查询:总是没有结果

0 投票
2 回答
2323 浏览
提问于 2025-04-16 00:04

我正在尝试用Python查询LDAP服务器,但总是没有结果。有没有人能帮我找出我的Python代码哪里出错了?代码运行得很好,没有报错,但就是没有结果。我试着修改了查询条件,比如“cn=partofmyname”,但还是没有成功。谢谢大家的帮助。

import ldap



try:
    l = ldap.open("server")
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)
    output =l.simple_bind("cn=username,cn=Users,dc=domian, dc=net",'password$R')
    print output
except ldap.LDAPError, e:
    print e

baseDN = "DC=domain,DC=net"
searchScope = ldap.SCOPE_SUBTREE
## retrieve all attributes - again adjust to your needs - see documentation for more options
retrieveAttributes = None

Filter = "(&(objectClass=user)(sAMAccountName=myaccount))"

try:
    ldap_result_id = l.search(baseDN, searchScope, Filter, retrieveAttributes)
    print ldap_result_id
    result_set = []
    while 1:
        result_type, result_data = l.result(ldap_result_id, 0)
        if len(result_data) == 0:
            print 'no reslut'
            break
        else:
            for i in range(len(result_set)):
                for entry in result_set[i]:
                    try:
                        name = entry[1]['cn'][0]
                        email = entry[1]['mail'][0]
                        phone = entry[1]['telephonenumber'][0]
                        desc = entry[1]['description'][0]
                        count = count + 1
                        print "%d.\nName: %s\nDescription: %s\nE-mail: %s\nPhone: %s\n" %\
                              (count, name, desc, email, phone)
                    except:
                        pass
                        ## here you don't have to append to a list
                        ## you could do whatever you want with the individual entry
            #if result_type == ldap.RES_SEARCH_ENTRY:
             # result_set.append(result_data)
            #  print result_set
except ldap.LDAPError, e:
    print e
l.unbind()

2 个回答

0

我强烈建议你使用Wireshark(www.wireshark.org)来查看网络流量,这样可以了解协议层面发生了什么。同时,你可以下载一个叫Softerra LDAP浏览器2.6的工具(可以在http://www.ldapbrowser.com/download.htm找到免费的版本),用来检查A/D服务器和目录的组织结构。

如果你还是遇到问题,可以把你用这些工具发现的情况总结一下发出来。

2

我找到了我的问题。

simple_bind("cn=username,cn=Users,dc=domian, dc=net",'password$R')

应该是

   simple_bind("domain/username",'password$R')

撰写回答