LDAP: How get all users belongs to a group.

Ken Watford kwatford+python at gmail.com
Thu Jun 23 09:59:46 EDT 2011


On Thu, Jun 23, 2011 at 9:14 AM, sajuptpm <sajuptpm at gmail.com> wrote:
> Hi,
> How get all users belongs to a group using python ldap module.

Depends on what you mean by "users" and "group", what information you
already have, and what information you want to get. I'll assume you
mean posix accounts and groups, and that you already know how to
connect to the LDAP server.

If you already know the distinguished name of the group, you can get a
list of the member names like so (ignoring error handling):

dn, entry = connection.search_s(group_dn, ldap.SCOPE_BASE)[0]
member_list = entry['memberUid']

That will only get you the usernames. If you need to get the user's
entry (or don't know the group_dn above), then you'll have to do a bit
more searching.

To find a user's entry given their uid:

results = connection.search_s(base_dn, ldap.SCOPE_SUBTREE, "(uid=*)")
for dn, entry in results:
     if uid in entry['uid']:
         # this is your guy. return, or break, or whatever

The "(uid=*)" filter just means to only find entries that have user id
fields. If you wanted to be more specific about it, you could limit it
to only posixAccount objects with "(objectClass=posixAccount)". This
would probably be necessary if you wanted to search for groups (via
"(objectClass=posixGroup)" ), since those don't have a special field
for their name - they usually just use the cn (common name) field for
that. A slightly more complex filter could be written to avoid the
python loop.

If your groups are not posixGroup objects but instead groupOfNames,
then the appropriate attribute is "member" rather than "memberUid",
and the values there are user DNs instead of uids. In that case, if
you need the uid you'll have to look up those users and pull it out.



More information about the Python-list mailing list