需要帮助使用python-ldap来查询我的LDAP服务器以获取用户名

时间:2017-08-28 12:54:08

标签: ldap openldap ldap-query python-ldap

我希望我的脚本只需查询LDAP,并为我提供属于我在SAMPLE_groupName变量中指定的任何组的所有用户的列表。

这是我的剧本

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()

这是输出

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

输出显示一个成员在coolGuys组中,这在我的情况下是正确的。所以这是我的问题...... 我怎样才能让输出简单地成为" jonny"而不是我上面那么长的输出?

1 个答案:

答案 0 :(得分:0)

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