Python-ldap的API使用

官网:python-ldap — python-ldap 3.4.3 documentation

下面是一个简单的 Python LDAP 代码示例,用于连接到 LDAP 服务器并检索用户信息:

import ldap

# Set the LDAP server URI and bind credentials
LDAP_URI = 'ldap://ldap.example.com'
LDAP_USERNAME = 'cn=admin,dc=example,dc=com'
LDAP_PASSWORD = 'adminpassword'

# Connect to the LDAP server
ldap_conn = ldap.initialize(LDAP_URI)
ldap_conn.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)

# Search for a user by their email address
search_filter = '(mail=user@example.com)'
search_base = 'ou=people,dc=example,dc=com'
attrs = ['uid', 'givenName', 'sn', 'mail']
result = ldap_conn.search_s(search_base, ldap.SCOPE_SUBTREE, search_filter, attrs)

# Print the user information
if result:
    dn, entry = result[0]
    uid = entry.get('uid', [''])[0]
    first_name = entry.get('givenName', [''])[0]
    last_name = entry.get('sn', [''])[0]
    email = entry.get('mail', [''])[0]
    print(f'User: {uid}\nFirst name: {first_name}\nLast name: {last_name}\nEmail: {email}')
else:
    print('User not found')

# Close the LDAP connection
ldap_conn.unbind()

这个示例连接到一个 LDAP 服务器,使用管理员凭据进行身份验证,然后搜索具有特定电子邮件地址的用户。它检索用户的 uid,名字,姓氏和电子邮件,并将它们打印到控制台上。最后,它关闭了 LDAP 连接。你可以根据需要修改搜索过滤器,搜索基础和属性列表。

实例:

import ldap

LDAP_SERVER = 'ldap://10.33.32.135'
LDAP_BIND = 'ou=People,dc=vivo,dc=lan'
LDAP_PASS = 'Lu2Kiaw'
BASE_DN = 'dc=vivo,dc=lan'
SEARCH_FILTER = '(&(objectClass=posixAccount)(uid=11136711))'

def ldap_search():
    ldap_conn = ldap.initialize(LDAP_SERVER)
    ldap_conn.protocol_version = 3
    ldap_conn.simple_bind(LDAP_BIND, LDAP_PASS)
    search_result = ldap_conn.search_s(BASE_DN, ldap.SCOPE_SUBTREE, SEARCH_FILTER)
    if search_result:
        for dn, attrs in search_result:
            print('DN: {}'.format(dn))
            for attr, value in attrs.items():
                print('{}: {}'.format(attr, value))
	else:
		print('No results found.')


if __name__ == '__main__':
	ldap_search()
#ldap_add_mem("141a49b683a57267e82f620889e3c887","72156781")

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值