解析列表以获得精确值

Parse a list to get exact value

我正在尝试通过 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]

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

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

Microsoft's site has information about LDAP search filters which are most likely relevant to AD. There are some examples about Wildcards

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

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

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