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

Python ldap3 how to get all members of a group

我已经尝试了 Whosebug 上的所有解决方案,并 none 工作。 使用 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