Python實現LDAP用戶名密碼驗證


網上借鑒了不少東西,下面是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("用戶名","密碼")

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM