欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python ldap实现登录实例代码

时间:2021-10-09 08:51:34|栏目:Python代码|点击:

下面一段代码是小编给大家介绍的Python ldap实现登录实例代码,一起看看吧

ldap_config = {
  'ldap_path': 'ldap://xx.xx.xx.xx:389',
  'base_dn': 'ou=users,dc=ledo,dc=com',
  'ldap_user': 'uid=reporttest,ou=users,dc=ledo,dc=com',
  'ldap_pass': '111111.0',
  'original_pass': '111111.0'
}
ldap_message = {
  0: 0, #'ok'
  1: 1, #'用户名或密码错误'
  2: 2, #ldap验证异常'
}
import ldap
import base64
import hashlib
from config_message import ldap_config, ldap_message
class LDAP_API(object):
  _ldap_path = ldap_config['ldap_path']
  _base_dn = ldap_config['base_dn']
  _ldap_user = ldap_config['ldap_user']
  _ldap_pass = ldap_config['ldap_pass']
  _original_pass = ldap_config['original_pass']
  # 连接ldap服务器
  def __init__(self):
    try:
      self.ldapconn = ldap.initialize(self._ldap_path)
      self.ldapconn.protocal_version = ldap.VERSION3
      self.ldapconn.simple_bind(self._ldap_user, self._ldap_pass)
    except ldap.LDAPError, e:
      print e
  # 验证用户登录
  def ldap_check_login(self, username, password):
    obj = self.ldapconn
    searchScope = ldap.SCOPE_SUBTREE
    # searchFilter = '(&(cn='+username+')(userPassword='+password+'))'
    searchFilter = 'uid=' + username
    try:
      obj.search(self._base_dn, searchScope, searchFilter, None) # id--2
      # 将上一步计算的id在下面运算
      result_type, result_data = obj.result(2, 0)
      if result_type != ldap.RES_SEARCH_ENTRY:
        return {'status': ldap_message[1], 'data': ''}
      dic = result_data[0][1]
      l_realname = dic['sn'][0]
      l_password = dic['userPassword'][0]
      md_password = LDAP_API.hash_md5(password)
      if l_password in (password, md_password):
        return {'status': ldap_message[0], 'data': l_realname}
      else:
        return {'status': ldap_message[1], 'data': ''}
    except ldap.LDAPError, e:
      return {'status': ldap_message[2], 'data': ''}
  @staticmethod
  def hash_md5(data):
    md = hashlib.md5()
    md.update(str(data))
    a = md.digest()
    b = '{MD5}' + base64.b64encode(a)
    return b

上一篇:Python实现购物车程序

栏    目:Python代码

下一篇:分享一个可以生成各种进制格式IP的小工具实例代码

本文标题:Python ldap实现登录实例代码

本文地址:http://www.codeinn.net/misctech/179296.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有