温馨提示×

python怎么获取ldap所有用户

小亿
144
2023-10-14 08:50:52
栏目: 编程语言

要获取LDAP(轻型目录访问协议)中的所有用户,可以使用python-ldap库。

首先,确保安装了python-ldap库。可以使用以下命令进行安装:

pip install python-ldap

下面是一个示例代码,演示如何连接到LDAP服务器并获取所有用户信息:

import ldap
# 连接到LDAP服务器
ldap_server = 'ldap://your_ldap_server'  # 替换为实际的LDAP服务器地址
ldap_base_dn = 'dc=example,dc=com'  # 替换为实际的LDAP基础DN
ldap_user = 'cn=admin,dc=example,dc=com'  # 替换为实际的LDAP管理员用户
ldap_password = 'password'  # 替换为实际的LDAP管理员用户密码
conn = ldap.initialize(ldap_server)
conn.simple_bind_s(ldap_user, ldap_password)
# 搜索所有用户
search_filter = '(objectClass=person)'
search_attribute = ['cn', 'mail']  # 指定要获取的属性列表
results = conn.search_s(ldap_base_dn, ldap.SCOPE_SUBTREE, search_filter, search_attribute)
# 打印用户信息
for dn, attrs in results:
print('User DN:', dn)
for attr, values in attrs.items():
print(attr + ':', values)
# 断开LDAP连接
conn.unbind()

在上面的示例代码中,首先使用ldap.initialize()方法初始化一个LDAP连接,然后使用conn.simple_bind_s()方法进行身份验证。接下来,使用conn.search_s()方法搜索所有用户。搜索时,指定了要搜索的基础DN、搜索范围、搜索过滤器和要获取的属性列表。最后,使用循环遍历结果,并打印每个用户的属性信息。

请根据实际情况替换示例代码中的LDAP服务器地址、基础DN、管理员用户和密码。

0