Need help using python-ldap to query my LDAP server for user names

3.2k views Asked by At

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

There are 1 answers

0
iNoob On BEST ANSWER
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