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

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

问题描述:

我想我的脚本简单地查询LDAP并给我一个属于我在SAMPLE_groupName变量中指定的任何组的所有用户的列表。需要帮助使用python-ldap来查询我的LDAP服务器的用户名

这是我的脚本

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”而不是我上面那长长的输出字符串?

+0

尝试使用具有相应权限的凭据进行绑定,以至少读取所有条目。 – jwilleke

+0

是啊我正在做一个绑定与适当的凭据。只是不知道如何让它只是返回一个用户名。另外请记住,这是在Linux机器上运行的openLdap –

+0

使用python-ldap我会执行搜索'restuls = l.search_s(searchBase,ldap.SCOPE_ONELEVEL,searchFilter,attrlist = ['*'])'然后抓取成员的成员= restuls [0] [1] ['member']'例如下面的答案 – iNoob

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