由于工作中有时候会遇到需要对AD域服务器进行批量添加用户和组织的操作,平时都是通过bat批处理对csv文件中的用户和组织进行操作添加,但是操作起来还是略麻烦,就想自己动手用Python代码写个更好操作的方式,随便百度了下,还真的有相关的库——ldap3,先写点demo,后面再完善下吧。
基本操作方法:
from ldap3 import Server, Connection, ALL, NTLM
# 连接
server = Server('192.168.214.93', get_info=ALL)
conn = Connection(server, user='TEST\\administrator', password='Winhong1234@#test', auto_bind=True, authentication=NTLM)
print(server.info)
# 查询
res = conn.search('dc=test,dc=csc,dc=com', '(objectclass=user)', attributes=['objectclass'])
print(conn.result) # 查询失败的原因
print(conn.entries) # 查询到的数据
# 增加组织
res = conn.add('OU=python,OU=cibuser,DC=test,DC=csc,DC=com', object_class='OrganizationalUnit')
if res:
print('增加组织成功!')
else:
print('增加组织发生错误')
if conn.result['description'] == 'entryAlreadyExists':
print('--该组织已存在')
# 增加用户
user01 = {
'displayName' : 'python测试用户01', # 显示名称
'userPrincipalName' : 'python_user_01@test.csc.com'