Python3-ldap KeyError:'属性'

时间:2014-08-14 17:45:06

标签: python python-3.x ldap

在加载了python3-ldap模块的情况下使用Python3.4。使用代码:

from ldap3 import Server, Connection, SEARCH_SCOPE_WHOLE_SUBTREE, AUTO_BIND_NO_TLS #For title queires into LDAP

def GetTitle(u):
    print(u)
    t=[]

    server = Server(DomanCtrlr)
    c = Connection(server,
                   auto_bind=AUTO_BIND_NO_TLS,
                   read_only=True,
                   check_names=True,
                   user = user,
                   password= password)

    c.search(search_base = 'dc=corp,dc=weyer,dc=pri',
             search_filter = '(&(samAccountName=' + u + '))',
             search_scope = SEARCH_SCOPE_WHOLE_SUBTREE,
             attributes = ['title'],
             paged_size = 5)

    for entry in c.response:
        print(entry['attributes']['title'])
        t = entry['attributes']['title']
        print(u, " : ", t)

users = ['user1', 'notAuser', 'user2']

for u in users:
    GetTitle(u)

我希望notAuser收到错误,但我得到了这个输出:

user1
['CONTROL ROOM OPERATOR']
user1  :  ['CONTROL ROOM OPERATOR']
Traceback (most recent call last):
  File "C:\Users\olsonma\Documents\ThreatMatrix_PY\LDAPTest.py", line 28, in <module>
    GetTitle(u)
  File "C:\Users\olsonma\Documents\ThreatMatrix_PY\LDAPTest.py", line 17, in GetTitle
    print(entry['attributes']['title'])
KeyError: 'attributes'

由于这条线明显执行,我不清楚错误是如何发生的。

我发现很多关于旧python-ldap错误的文章与此类似,但是为python-ldap修复它的选项并不是python3-ldap的选项。有人知道吗 1.)为什么会这样? 2.)如何让它停止?

1 个答案:

答案 0 :(得分:1)

自从我找到问题后,已从代码中删除了打印件。

from ldap3 import Server, Connection, SEARCH_SCOPE_WHOLE_SUBTREE, AUTO_BIND_NO_TLS #For title queires into LDAP

def GetTitle(u):

    t=''

    server = Server(DomainCtrlr)
    c = Connection(server,
                   auto_bind=AUTO_BIND_NO_TLS,
                   read_only=True,
                   check_names=True,
                   user = user,
                   password= password)

    c.search(search_base = 'dc=corp,dc=weyer,dc=pri',
             search_filter = '(&(samAccountName=' + u + '))',
             search_scope = SEARCH_SCOPE_WHOLE_SUBTREE,
             attributes = ['title'],
             paged_size = 5)

   if len(c.response) > 1:
        for entry in c.response:
            t = entry['attributes']['title']
            return t

users = ['lafrenh', 'userid', 'garlockb']

for u in users:
    title = GetTitle(u)
    print(title)