python ldap3获取所有用户信息_Python使用Ldap3进行Windows AD域管理

本文介绍了如何使用Python的ldap3库连接到Windows Active Directory(AD)服务器,进行用户信息搜索、账户启用禁用及密码修改等操作。首先通过pip安装ldap3库,然后设置服务器和建立连接,接着展示不同类型的搜索方法,最后演示了启用/禁用用户账户和修改用户密码的代码示例。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

一、安装

pip install ldap3

二、基本使用

1. 设置服务器

1.1 设置单个服务器

server=Server('192.168.1.1',use_ssl=True,get_info=ALL)

1.2 设置多个服务器

Ad_IP_List=['192.168.1.1','192.168.1.2'] #设置服务器列表

Server_pool = ServerPool(None) #声明服务器连接池

#遍历服务器列表,将服务器添加至服务器连接池

for line in Ad_IP_List:

server = Server(line, use_ssl=True, get_info=ALL)

Server_pool.add(server)

备注:如要对AD进行修改操作,需要使用use_ssl=True参数,否则无法正常执行。

2. 建立连接

2.1 连接服务器

2.1.1 连接单个服务器

conn = Connection(Server, user=Ad_M_User, password=Ad_M_Passwd, authentication=NTLM, auto_bind=True)

2.1.2 根据服务器池进行连接

conn = Connection(Server_pool, user=Ad_M_User, password=Ad_M_Passwd, authentication=NTLM, auto_bind=True)

2.2 查看连接状态

>>> conn

Connection(server=Server(host='192.168.1.1', port=636, use_ssl=True, allowed_referral_hosts=[('*', True)], tls=Tls(validate=), get_info='ALL', mode='IP_V6_PREFERRED'), user='domain\administrator', password='123456', auto_bind='NO_TLS', version=3, authentication='NTLM', client_strategy='SYNC', auto_referrals=True, check_names=True, read_only=False, lazy=False, raise_exceptions=False, fast_decoder=True, auto_range=True, return_empty_attributes=True, auto_encode=True, auto_escape=True, use_referral_cache=False)

3. 搜索

3.1 搜索AD基本信息

>>> conn.search(search_base='',search_filter='(objectClass=*)',search_scope=BASE,attributes=['*'])

>>> conn.entries

例:通过搜索AD,输出DN。conn.entries命令输出搜索内容

DN=str(conn.entries[0]['rootDomainNamingContext']).split(': ')[0]

3.2 搜索OU

下列DN变量为: DN=’OU=Group,OU=Group,DC=it,DC=baidu,DC=com’

>>> conn.search(DN,'(ou=*)')

3.3 搜索OU下面的所有用户

>>> conn.search(Group_DN, '(objectclass=person)', attributes=ALL_ATTRIBUTES)

3.4 搜索单个用户所有信息

>>> conn.search(DN, "(sAMAccountName=ADMIN)", attributes=['*'])

3.5 搜索单个用户的OU信息

>>> conn.search(DN, "(sAMAccountName=ADMIN)", attributes=['distinguishedName'])

4.操作AD

4.1 启用或禁用帐户

下列CN变量为: CN=’CN=UserName,OU=Group,OU=Group,DC=it,DC=baidu,DC=com’

4.1.1 启用帐号:66048 为密码永不过期 及启用帐号 单启用帐号为 512

>>> conn.modify(CN, {'userAccountControl': [(MODIFY_REPLACE, ['66048'])]})

4.1.2 禁用帐号:66050 为密码永不过期 及禁用帐号 单禁用帐号为 514

>>> conn.modify(CN, {'userAccountControl': [(MODIFY_REPLACE, ['66050'])]})

4.2 修改用户密码

>>> conn.extend.microsoft.modify_password(OU, '123456')

文档:

2019-7-8 17:4:50

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值