ldapadd.py
#-*- coding:utf-8 -*-
from ldap3 import Server, Connection, ALL
# define the server
s = Server(host='ldap.example.com', port=389,get_info=ALL)
# define the connection
c = Connection(s, user='cn=admin,dc=example,dc=com', password='123456')
# perform the Bind operation
if not c.bind():
print('error in bind', c.result)
#ldap添加用户
def adduser(line,ldap_dn,ldap_attributes):
c.add(dn=ldap_dn,
object_class=['inetOrgPerson', 'top'],
attributes=ldap_attributes)
#打印报错信息和报错数据
if c.result['result'] != 0:
print(c.result,' ===添加失败===> ' + line)
with open('E:\python\ldapuser','r',encoding='utf8') as f:
for line in f.readlines():
ldap_attributes = {}
dn_cn=(line.replace('\n','').split('|')[0])
dn_sn=(line.replace('\n','').split('|')[1])
# dn_ou=(line.replace('\n','').split('|')[2])
ldap_password=(line.replace('\n','').split('|')[2])
ldap_mail=(line.replace('\n','').split('|')[3])
ldap_mobile=(line.replace('\n','').split('|')[4])
ldap_dn='cn=%s,ou=技术部,dc=example,dc=com'%(dn_cn)
ldap_attributes={'sn': dn_sn,
'userpassword': ldap_password,
'mail': ldap_mail,
'mobile': ldap_mobile}
# print(ldap_dn,ldap_attributes)
adduser(line,ldap_dn,ldap_attributes)
c.unbind()
ldapuser
wangfeng|王五|123456|wangwu@example.com|15012345678
zhangsan|张三|123456|zhangsan@example.com|15012345678
#设置密码的时候最好不要有 |
cn | sn | password | mail | mobile