python3 操作open ldap

##pip3.7 install python-ldap==3.3.1


import ldap
from ldap import modlist
ldapconn = ldap.initialize('ldap://192.168.3.99:389',bytes_mode=False) ###python3一定要加上bytes_mode=False 这个参数,否则会报错
ldapconn.simple_bind('cn=admin,dc=xthktech,dc=cn','xxxxx')

#验证用户密码
try:
ldapconn.simple_bind_s('uid=0000,ou=people,dc=xthktech,dc=cn','xxx')
print('登录成功')
except ldap.INVALID_CREDENTIALS as e:
print('用户名或密码错误')

#修改用户密码
try:
res = ldapconn.passwd_s('uid=test,ou=people,dc=xthktech,dc=cn','xxxx','44')
print('密码更改成功')
except ldap.UNWILLING_TO_PERFORM as e:
print('旧密码验证错误')

#搜索用户信息
searchScope = ldap.SCOPE_SUBTREE
searchFilter = 'uid=0000'
base_dn = 'ou=people,dc=xthktech,dc=cn'
res = ldapconn.search_s(base_dn, searchScope, searchFilter, None)
if len(res) == 0:
print('not found')
else:
print(res)


#修改用户信息
old = {'mail':[b'ffff@qq.com'],'sn':[b'test']}
new = {'mail':[b'loveyou@qq.com'],'sn':[b'fuckyou']}
ldif =modlist.modifyModlist(old,new)
ldapconn.modify_s('uid=test,ou=people,dc=xthktech,dc=cn',ldif)
ldapconn.unbind_s()

#新增用户
try:
attrs = {}
attrs['objectclass'] = [b'inetOrgPerson']
attrs['cn'] = [b'zhang san']
attrs['uid'] = [b'test']
attrs['sn'] = [b'xx']
attrs['telephoneNumber'] = [b'10222222222']
attrs['mail'] = [b'ff@qq.com']
attrs['userPassword'] = []
ldif = modlist.addModlist(attrs)
s=ldapconn.add_s('uid=test,ou=people,dc=xthktech,dc=cn',ldif)
print(s)
print('ok')
except ldap.ALREADY_EXISTS as e:
print('数据库已经存在该用户')
try:
ldapconn.passwd_s('uid=xxxx,ou=people,dc=xthktech,dc=cn',None,'123456')
except Exception as e:
print(e)
ldapconn.unbind_s()

#删除用户
try:
ldapconn.delete_s('uid=888,ou=people,dc=xthktech,dc=cn')
print('删除用户成功')
except ldap.NO_SUCH_OBJECT as e:
print('数据库中没有找到该用户')

posted on 2021-02-03 16:53  it_man_xiangge  阅读(744)  评论(0编辑  收藏  举报

导航

所有文章均为个人学习笔记,并未有任何教学的意思,大神勿喷