zoukankan      html  css  js  c++  java
  • 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("用户名","密码")
     
  • 相关阅读:
    矩阵——矩阵介绍
    CentOS6.6x86_64 部署 Nginx1.62+MySQL5.6.20+PHP5.6.4
    Linux Stu
    Linux Tips
    网页嵌入百度地图和使用百度地图api自定义地图的详细步骤
    商务通被视频覆盖
    酷炫的响应式导航栏
    织梦DeDeCms列表分页和内容页分页错位解决办法
    form表单中method的get和post区别
    PC端手机访问跳转手机站点
  • 原文地址:https://www.cnblogs.com/chuanheng/p/Python_LDAP_Auth.html
Copyright © 2011-2022 走看看