网上借鉴了不少东西,下面是python代码,备份后用。
思路,因为每个用户的组都不一样,这样就导致了dn不一致的情况,
据需要先根据用户名获取该用户的dn,然后再bind用户名和密码进行验证。
反正是实现了,至于方式对不对后续再研究了。
机器上要先安装python-ldap包
1 #coding: utf-8 2 import ldap 3 ‘‘‘ 4 实现LDAP用户登录验证,首先获取用户的dn,然后再验证用户名和密码 5 ‘‘‘ 6 7 ldappath = "ldap://xxxx"#ldap服务器地址 8 baseDN = "DC=aaaa,DC=bbbb,DC=com"#根目录 9 ldapuser = "xxxx";#ldap服务器用户名 10 ldappass = "xxxx";#ldap服务器密码 11 12 #获取用户的dn 13 def _validateLDAPUser(user): 14 try: 15 l = ldap.initialize(ldappath) 16 l.protocol_version = ldap.VERSION3 17 l.simple_bind(ldapuser,ldappass) 18 19 searchScope = ldap.SCOPE_SUBTREE 20 searchFiltername = "sAMAccountName" 21 retrieveAttributes = None 22 searchFilter = ‘(‘ + searchFiltername + "=" + user +‘)‘ 23 24 ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes) 25 result_type, result_data = l.result(ldap_result_id,1) 26 if(not len(result_data) == 0): 27 r_a,r_b = result_data[0] 28 print r_b["distinguishedName"] 29 return 1, r_b["distinguishedName"][0] 30 else: 31 return 0, ‘‘ 32 except ldap.LDAPError, e: 33 print e 34 return 0, ‘‘ 35 finally: 36 l.unbind() 37 del l 38 39 #连接超时,尝试多次连接 40 def GetDn(user, trynum = 30): 41 i = 0 42 isfound = 0 43 foundResult = "" 44 while(i < trynum): 45 isfound, foundResult = _validateLDAPUser(user) 46 if(isfound): 47 break 48 i+=1 49 return foundResult 50 51 def LDAPLogin(userName,Password): 52 try: 53 if(Password==""): 54 print "PassWord empty" 55 return 56 dn = GetDn(userName,10) 57 if(dn==‘‘): 58 print "Not Exist User" 59 return 60 my_ldap = ldap.initialize(ldappath) 61 print my_ldap.simple_bind_s(dn,Password) 62 print "Login Ok" 63 except Exception,e: 64 print "Login Fail" 65 # print str(e) 66 67 LDAPLogin("用户名","密码")