使用包ldap3进行Python的LDAP操作2

本文介绍了使用Python进行LDAP认证的方法,并提供了详细的代码示例。包括如何连接到LDAP服务器、执行搜索操作以及验证用户密码等关键步骤。

我的ldap操作代码。

访问LDAP:

import os
import hashlib
import unittest

import sysmgt.sysconf as sysconf

from ldap3 import Connection,Server

#LDAP服务器信息存放在配置文件中。
_server_ip= sysconf.get_property('ldap.server')
_user_id  = sysconf.get_property('ldap.userid')
_passwd   = sysconf.get_property('ldap.passwd')
_port     = sysconf.get_property('ldap.port')
_baseDN   = sysconf.get_property('ldap.baseDN')

# bind就等于login
_connection = Connection(Server(_server_ip,port=int(_port)),user=_user_id,password=_passwd,auto_bind=True)

def test_LDAP():
	print 'server_ip = ',_server_ip
	print 'user_id   = ',_user_id
	print 'passwd    = ',_passwd
	print 'port      = ',_port
	print 'baseDN    = ',_baseDN
	server=Server(_server_ip,port=int(_port))
	conn=Connection(server,user=_user_id,password=_passwd)
	print server
	print conn
	print conn.bind()
	#print server.info
	#print server.schema
	print conn.extend.standard.who_am_i()
	print hasattr(conn,'entries')
	conn.search('ou=users,'+_baseDN,'(&(uid=hanmj1)(objectclass=person))',attributes=['uid','mail','userPassword'])
	if hasattr(conn,'entries'):
		ens=conn.entries
		for e in ens:
			print '*'*20
			print e
			print e['userPassword']
			print type(e['userPassword'])
			#print dir(e['userPassword'])
			print _checkPassword(str(e['userPassword']),'hanmj1x')
			#print dir(e)

检查密码是否正确:

def check_user(username,password):
	'''
	connection to LDAP and check whether user exists
	return str and '' means password correct, otherwise it means error message
	'''
	_connection.search('ou=users,'+_baseDN,'(&(uid='+username+')(objectclass=person))',attributes=['uid','userPassword'])
	if hasattr(_connection,'entries'):
		ens=_connection.entries
		if len(ens)==1:
			pwd=str(ens[0]['userPassword'])
			if _checkPassword(pwd,password):
				return ''
			else:
				return 'password not correct'
		elif len(ens)>1:
			return 'too many users'
	return 'user not found'


def _makeSecret(password):
    salt = os.urandom(4)
    h = hashlib.sha1(password)
    h.update(salt)
    return "{SSHA}" + encode(h.digest() + salt)

def _checkPassword(challenge_password, password):
    challenge_bytes = decode(challenge_password[6:])
    digest = challenge_bytes[:20]
    salt = challenge_bytes[20:]
    hr = hashlib.sha1(password)
    hr.update(salt)
    return digest == hr.digest()
'''
>>> challenge_password = _makeSecret('testing123')

>>> challenge_password
    '{SSHA}0c0blFTXXNuAMHECS4uxrj3ZieMoWImr'

>>> _checkPassword(challenge_password, 'testing123')
    True

>>> _checkPassword(challenge_password, 'testing124')
    False
'''

 

转载于:https://my.oschina.net/shawnplaying/blog/733608

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值