Python ldap3如何获取一个组的所有成员



为此,我在Stackoverflow上尝试了所有解决方案,但都不起作用。使用python3和ldap3,我可以与用户和服务帐户绑定,甚至可以提取用户的电子邮件地址。但我无法证实他是否来自某个群体。我正在努力争取小组的所有成员,然后我会看看他是否在那个小组中。

用户DN:OU=Users,O=Acme谁是:CN=my Users,OU=MyUsers,OU=Groups,O=Acme的成员

这是我目前掌握的代码。。

try:
l = bind_user(MyServiceAccount, MyServiceAccountPassword)
except Exception as e:
logger.info(f'Error attempting to bind with ldap server: {e}')
return(f'Error logging in. Details: {e}')
#### This first search works and returns the users email address ###
search_filter = f"(cn={user_name})"
search_attribute =['mail']
l.search(search_base='OU=Users,O=Acme',
search_scope=SUBTREE,
search_filter=search_filter,
attributes=search_attribute)
print('l.response',l.response)
email = l.response[0]['attributes']['mail'] # All Good to here


### This next search does not work. it just returns and empty list 
l.search(
search_base='CN=my-users,OU=MyUsers,OU=Groups,O=Acme',
search_filter='(cn=my-users)',
search_scope='SUBTREE',
attributes = ['member'],
size_limit=0
)

print(f'printing entries = {l.entries}') # Outputs []
print(f'Group response = {l.response}') # This also outputs []

for entry in l.entries: # Never happens
print(entry.member.values)

如果你只需要验证你的用户是我的用户的成员,那么你不需要第二次搜索。相反,添加搜索属性";memberOf";search_attribute =['mail', 'memberOf']到您的第一次搜索,然后以与邮件相同的方式解析它。像这样的。。

user_group_dn = 'CN=my-users,OU=MyUsers,OU=Groups,O=Acme'
search_filter = f"(cn={user_name})"
search_attribute =['mail', 'memberOf']
l.search(search_base='OU=Users,O=Acme',
search_scope=SUBTREE,
search_filter=search_filter,
attributes=search_attribute)
print('l.response',l.response)
email = l.response[0]['attributes']['mail'] 
memberOf = l.response[0]['attributes']['memberOf'] #This is the key
#memberOf should bring back ['CN=my-users,OU=MyUsers,OU=Groups,O=Acme','Someothe user groups']
if user_group_dn in memberOf:
# do some stuff here. allow login

相关内容

最新更新