0

如果已经问过这个问题,请提前道歉,已经做了一些搜索但没有运气。

TL;DR:试图将元组的第二部分作为字符串拉出。

我正在使用 python3 构建一个脚本,该脚本从 LDAP 中提取信息并返回希望是可操作的数据。

def GetMembersWDept():
    i2 = input('Please input the department number. Examples: 2410, 2417\n')
    criteria = '(&(objectClass=User)(department=' + i2 + '*))'
    print ('Search criteria set to: \t\t' + criteria)
    searchDC = 'dc=example,dc=com'
    print ('Searching location: \t\t\t' + searchDC)
    print ()
    out = []
    result = c.search(searchDC, criteria, \
        SEARCH_SCOPE_WHOLE_SUBTREE, attributes = ['department'])  \
        # request a few object from the ldap server
    if result:
        for r in c.response:
            if (r['type'] == 'searchResEntry'):
                out.append(r['dn'])
                out.append(r['attributes']) # comes out in tuple form
            else:
                pass
    else:
        print('result', conn.result)
    return out

这适用于提取该部门成员的 CN,但不适用于提取任何附加信息,在本例中是附加的部门。

示例输出为:

搜索条件设置为:(&(objectClass=User)(department=2417*)) 搜索位置:dc=ple,dc=com

['CN=First Last,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}, 'CN=Another Person,OU=ex,OU=am, DC=ple,DC=com', {'部门': ['1234']}]

如何将元组的第二部分(即“1234”)作为字符串提取出来?这里的最后阶段是将数据格式化为:

[第一个最后,1234,另一个人,1234]

...所以我可以在另一个比较部门并在不满足条件时返回名称的函数中使用它。

4

2 回答 2

2

如果输出是:

['CN=First Last,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}, 'CN=Another Person,OU=ex,OU=am,DC=ple,DC=com', {'department': ['1234']}]

然后您可以将其设置为等于newresult并执行以下操作:

print(list(newresult[1].values())[0][0])

这假定列表中包含部门的元素始终位于位置 1,字典始终具有 1 个值,并且您想要的部门编号是列表中的唯一项目。

于 2014-11-07T16:35:06.607 回答
0

恕我直言,使用它会更简单,c.search_s而不是c.search,除非您有充分的理由这样做(或者您应该展示您是如何创建响应的)。

来自 python-ldap 文档: search_s直接返回 2 元组(dn, attrs) 的列表,其中 dn 是包含条目的 DN(可分辨名称)的字符串,而 attrs 是包含与条目关联的属性的字典。attrs 的键是字符串,关联的值是字符串列表

因此,对于您拥有的每个元组entry

dn = entry[0]
departement = entry[1]{'department'}[0]
于 2014-11-07T16:55:06.927 回答