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|wangfeng@example.com|15012345678
zhangsan|张三|123456|wangfeng@example.com|15012345678
#设置密码的时候最好不要有  | 
cn  | sn  |  password |  mail |  mobile

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

open