0
votes

I want my script to simply query the LDAP and give me a list of all users that belong to whatever group I specify in the SAMPLE_groupName variable.

This is my script

server = 'ldap://myserver'

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

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

pw = "password"
filter = '(objectclass=*)'
attrs = ['member']

con = ldap.initialize(server)

try:
    con.start_tls_s()
    con.simple_bind_s(dn,pw)
    print con.search_s(base, ldap.SCOPE_SUBTREE, filter, attrs)
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 "unbinding."
    con.unbind()

And here is the output

[('cn=coolGuys,cn=groups,cn=accounts,dc=example,dc=com', {'member',['uid=jonny,cn=users,cn=accounts,dc=openstack,dc=local']})]

The output shows that one member is in the coolGuys group which is true in my case. So here is my question... How can I have the output simply be "jonny" and not that long string of output I have above?

1
Try binding with credentials that have appropriate permissions to at least read all entries.jwilleke
yeah I am doing a bind with appropriate credentials. Just not sure how to get it to simply return a username. Also keep in mind that this is openLdap running on a Linux machineJoey Corkey
using python-ldap I would carry out the search 'restuls = l.search_s(searchBase, ldap.SCOPE_ONELEVEL, searchFilter, attrlist=['*'])' then grab members 'members = restuls[0][1]['member']' example as answer belowiNoob

1 Answers

0
votes
def group_check(group, l):
    full_paths = []
    searchFilter = '(&(cn=*{}*))'.format(group)
    searchBase = 'OU=THISOU,DC=Company,DC=Domain,DC=com'
    restuls = l.search_s(searchBase, ldap.SCOPE_ONELEVEL, searchFilter, attrlist=['*'])
    try:
        if restuls:
            print 'Members Of {}\n'.format(group)
            members = restuls[0][1]['member']
            for mem in members:
                print '\t' + str(mem).split(',')[0].split('=')[1]
                full_paths.append(mem)

    except KeyError:
        print '\nNo Members? {}'.format(user)
    except Exception,e:
        print e