在python3上实现微软域帐号ldap登陆认证
有任务要实现域帐号认证,分别试用了ldap,python-ldap包后发现都是基于python2的
在python3上试用基本全部失败,ldap网上和官方代码基本跑不了
python-ldap包直接只支持python2安装不上,在改了部分代码后放弃
主要是在win下修改代码,边改边跑这两个包,N多努力后,偶然看见电脑里有ldap3这样一个控件包
并非主动安装,而是在python-ldap包时发现它引用的ldap包,顺腾摸瓜准备改代码时发现的
然后利用ldap3包如愿实现了所需要的功能,过程略折腾,因为网上的代码要么跑不动,要么有些在win下看似可以,实则不行
造成误会, 下面的代码在centos7.2 和python3.6下测试通过
接下来上代码:
from ldap3 import Server, Connection, ALL, NTLM
LDAP_URI = '10.86.87.52'
LDAP_USER = 'geely\\Huang.Xiaogang' #域和用户之间必须是双斜划线
LDAP_PASS = 'xxx'
BASE_DN = 'OU=GeelyStaff,dc=geely,dc=auto'
1.验证登陆 成功True 反之
server = Server(LDAP_URI, get_info=ALL)
conn = Connection(server, user=LDAP_USER, password=LDAP_PASS, authentication= NTLM)
print(conn.bind())
2.返回基本信息
print(conn.extend.standard.who_am_i())
u:GEELY\Huang.XiaoGang
3.ssl登陆
server = Server('ipa.demo1.freeipa.org', use_ssl=True, get_info=ALL)
conn = Connection(server, 'uid=admin, cn=users, cn=accounts, dc=demo1, dc=freeipa, dc=org', 'Secret123', auto_bind=True)
4.ssl第二种方法
from ldap3 import Server, Connection, Tls
import ssl
tls_configuration = Tls(validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1)
server = Server('ipa.demo1.freeipa.org', use_ssl=True, tls=tls_configuration)
conn = Connection(server)
conn.open()
5.搜索用户
from ldap3 import Server, Connection, ALL
server = Server('ipa.demo1.freeipa.org', get_info=ALL)
conn = Connection(server, 'uid=admin, cn=users, cn=accounts, dc=demo1, dc=freeipa, dc=org', 'Secret123', auto_bind=True)
conn.search('dc=demo1, dc=freeipa, dc=org', '(objectclass=person)')
conn.entries #array
6.检查密码
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
'''