python怎么获取ldap所有用户

28次阅读
没有评论

共计 938 个字符,预计需要花费 3 分钟才能阅读完成。

要获取 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、管理员用户和密码。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计938字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)