解析列表以获取准确的值

时间:2019-03-27 13:35:36

标签: python python-3.x list ldap ldap3

我正在尝试通过LDAP查询Active Directory以列出组,但是我得到的信息比我所需的更多。如何解析结果以仅获取所有组名。例如:LOCAL_java_read和其他,而不是其余部分。

from ldap3 import Server, Connection, ALL
server = Server('xxx', port=389, get_info=ALL)
conn = Connection(server, 'username', 'password', auto_bind=True, raise_exceptions=True)
conn.search('OU=Groups,OU=CH,DC=google,DC=com', '(objectclass=group)')
groups=conn.entries
print (groups)

结果:

[DN: CN=LOCAL_java_read,OU=Groups,OU=CH,DC=google,DC=com - STATUS: Read - READ TIME: 2019-03-27T14:22:08.072330
, DN: CN=LOCAL_python_read,OU=Groups,OU=CH,DC=google,DC=com - STATUS: Read - READ TIME: 2019-03-27T14:22:08.072330
, DN: CN=LOCAL_php_read,OU=Groups,OU=CH,DC=google,DC=com - STATUS: Read - READ TIME: 2019-03-27T14:22:08.072330]

2 个答案:

答案 0 :(得分:0)

我不确定Active Directory如何构造其属性,但是我相信您可以使用通配符*通过更改搜索来获取组。

conn.search('OU=Groups,OU=CH,DC=google,DC=com', '(&(objectClass=group)(CN=*))')

Microsoft's site包含有关LDAP搜索过滤器的信息,这些信息很可能与AD有关。有一些有关Wildcards

的示例

答案 1 :(得分:0)

您可以使用正则表达式从各个组条目中提取组名:

import re
stripped_groups = [re.sub(r'^.+? CN=([^,\s]+),?.*$', r'\1', str(entry)) for entry in groups]
print(stripped_groups)

尽管我认为@Nathan McCoy的回答可能最终会导致更清洁,更好的解决方案。