欢迎访问宙启技术站
智能推送

Python中LDAP搜索操作的示例代码

发布时间:2023-12-17 17:04:14

LDAP(Lightweight Directory Access Protocol)是一种用于访问和维护分布式目录信息的协议。在Python中可以使用ldap3库来进行LDAP搜索操作。

下面是一个示例代码,展示了如何使用ldap3库进行LDAP搜索操作,并输出搜索到的结果。

from ldap3 import Connection, Server, ALL

# 设置LDAP服务器的地址、端口和协议版本
server = Server('ldap://ldap_server_address', port=389, use_ssl=False, get_info=ALL)

# 创建LDAP连接
conn = Connection(server, user='username', password='password', auto_bind=True)

# 设置要搜索的基准DN和搜索过滤条件
base_dn = 'ou=users,dc=example,dc=com'
search_filter = '(cn=John Smith)'

# 执行搜索操作
conn.search(base_dn, search_filter)

# 获取搜索结果
entries = conn.entries

# 输出搜索到的结果
for entry in entries:
    print(f'DN: {entry.entry_dn}')
    for attribute in entry.keys():
        print(f'{attribute}: {entry[attribute]}')

# 关闭LDAP连接
conn.unbind()

上述代码的实现步骤如下:

1. 导入ConnectionServerALL模块。

2. 创建一个Server对象,用于指定LDAP服务器的地址、端口和协议版本。

3. 创建一个Connection对象,用于建立与LDAP服务器的连接。在这里需要指定LDAP服务器的地址、端口以及用户凭证(用户名和密码)等信息。

4. 设置要搜索的基准DN和搜索过滤条件。

5. 执行搜索操作,conn.search(base_dn, search_filter)

6. 获取搜索结果,entries = conn.entries

7. 遍历搜索结果,并输出搜索到的DN和属性。

8. 关闭LDAP连接,conn.unbind()

下面是一个使用实例,假设我们在LDAP服务器上搜索员工的信息,并输出他们的姓名和邮箱。

from ldap3 import Connection, Server, ALL

# 设置LDAP服务器的地址、端口和协议版本
server = Server('ldap://ldap_server_address', port=389, use_ssl=False, get_info=ALL)

# 创建LDAP连接
conn = Connection(server, user='username', password='password', auto_bind=True)

# 设置要搜索的基准DN和搜索过滤条件
base_dn = 'ou=users,dc=example,dc=com'
search_filter = '(objectClass=person)'

# 执行搜索操作
conn.search(base_dn, search_filter)

# 获取搜索结果
entries = conn.entries

# 输出搜索到的结果
for entry in entries:
    # 获取姓名和邮箱属性
    name = entry['cn'][0]
    email = entry['mail'][0]
    print(f'姓名: {name}')
    print(f'邮箱: {email}')
    print('')

# 关闭LDAP连接
conn.unbind()

上述代码中,我们使用(objectClass=person)作为搜索过滤条件,表示只搜索类别为person的对象。然后使用entry['cn'][0]获取姓名属性,使用entry['mail'][0]获取邮箱属性,并输出结果。

总结:

本文介绍了如何使用ldap3库进行LDAP搜索操作的示例代码,并提供了一个实际使用的例子。你可以根据自己的需求进行相应的修改和扩展。