如何使用Python连接ldap
好多使用ldap认证的软件都是Python的,比如superset和airflow, 好吧,他们都是airbnb家的。在配置ldap的时候可能会出现认证失败,你不知道是因为什么导致配置失败的。所以,就要
跟踪源码,看看内部怎么认证实现的。
具体来实现如下:
启动
docker run -it ryan/python:3 /bin/bash
下载ldap3
pip install ldap3
测试连接
root@5edee218d962:/# python
Python 3.7.4 (default, Jul 13 2019, 14:20:24)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, LEVEL, SUBTREE
>>> server = Server('172.17.0.2', get_info=ALL)
>>> conn = Connection(server, 'cn=admin,dc=demo,dc=com', 'admin', auto_bind=True)
>>> conn.extend.standard.who_am_i()
'dn:cn=admin,dc=demo,dc=com'
测试登录部分
登录源码如下:
@staticmethod
def try_login(username, password):
conn = get_ldap_connection(configuration.conf.get("ldap", "bind_user"),
configuration.conf.get("ldap", "bind_password"))
search_filter = "(&({0})({1}={2}))".format(
configuration.conf.get("ldap", "user_filter"),
configuration.conf.get("ldap", "user_name_attr"),
username
)
search_scope = LEVEL
if configuration.conf.has_option("ldap", "search