Need help forming python-ldap query to list group members

13.8k Views Asked by At

Running this script on linux machine with openldap

WHY DOES THIS NOT LIST USERS WITHIN THE GROUPS... it only lists groups...no one can seem to figure this out...please help...

server = 'ldap://myAddress'

dn = 'uid=bill,cn=users,cn=accounts,dc=example,dc=com'

base = 'cn=coolPeople,cn=accounts,dc=example,dc=com'

pw = "password"
filter = '(objectclass=posixgroup)'
attrs = ['memberuid']

con = ldap.initialize(server)

try:
    con.start_tls_s()
    con.simple_bind_s(dn,pw)
    groups = con.search_s(base, ldap.SCOPE_SUBTREE, filter, attrs)
    for a in groups:
        print 'Group:', a[0]
        print 'Members:', a[-1].get('memberuid')
except ldap.INVALID_CREDENTIALS:
    print "Your username or password is incorrect."
    sys.exit()
except ldap.LDAPError, e:
    if type(e.message) == dict and e.message.has_key('desc'):
        print e.message['desc']
    else:
        print e
    sys.exit()
finally:
    print "Doing unbind."
    con.unbind()

Results:

Group: cn=g1,cn=groups,cn=accounts,dc=example,dc=com
Members: None
Group: cn=g2,cn=groups,cn=accounts,dc=example,dc=com
Members: None
Group: cn=coolPeople,cn=groups,cn=accounts,dc=example,dc=com
Members: None
Doing unbind.

I have plenty of users in my groups but can't seem to list them out using python-ldap

3

There are 3 best solutions below

1
On

Alright, I'm going to post this even tho this thread is quite old. However I often fall onto this thread while looking for answers.

If others like me want to access all users in groups or anything to do with LDAP really, the best way I found is as follow. It will create a list with 2 items, and a dictionary as the 2nd item, which contains all the data of the user.

The following code contains all the information you need, entirely, you can access it with .get(''), as it will contain every single object in the AD attached to the users. Your groups will be a list under the dict 'memberOf'.

import ldap

con = ldap.initialize('ldap://1.2.3.4')
user_dn = r"[email protected]"
password = "yourpassword"
  
try:
    con.simple_bind_s(user_dn, password)
    res = con.search_s("DC=domain, DC=local", ldap.SCOPE_SUBTREE, '(objectClass=*)')
    for i in res:
        if i[1].get('memberOf') is not None:
            print(str(i[1].get('sAMAccountName')) + ' - ' + str(i[1].get('memberOf')))

except Exception as e:
    print(e)
0
On

I'm not sure why your listing fails, but I thing your base is wrong.

try to go up in the branches and see if that helps:

base = 'cn=accounts,dc=example,dc=com'

base = 'dc=example,dc=com'
0
On

python-ldap returns search results as string-keyed dictionaries. The strings used as dict keys are case-sensitive (in opposite to LDAP attribute type names).

Probably the LDAP server returns this old attribute with its camel-cased name memberUid (see RFC 2307).

So this code change should bring you one step further:

a[-1].get('memberUid')