我成功地完成了 ldap 连接。怎么去:
1.我有python v 3.7.2
2.安装python-ldap:为此我尝试了“ pip install python-ldap ”,但它在Windows机器上对我不起作用,所以我使用下面的替代方法。
3.安装ldap去这里:https ://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap
并下载python_ldap‑3.1.0‑cp37‑cp37m‑win_amd64.whl
4.现在移动到下载目录并运行“ pip install python_ldap‑3.1.0‑cp37‑cp37m‑win_amd64.whl ”
- 现在打开 python shell 并检查“import ldap”如果你没有收到错误意味着你已经完成了。
这是示例代码:
#Resource of code :https://gist.github.com/ibeex/1288159
import ldap
def check_credentials(username, password):
"""Verifies credentials for username and password.
Returns None on success or a string describing the error on failure
# Adapt to your needs
"""
LDAP_SERVER = 'xxx'
# fully qualified AD user name
LDAP_USERNAME = '%s@spi.com' % username
# your password
LDAP_PASSWORD = password
base_dn = 'DC=spi,DC=com'
ldap_filter = 'userPrincipalName=%s@spi.com' % username
attrs = ['memberOf']
try:
# build a client
ldap_client = ldap.initialize(LDAP_SERVER)
# perform a synchronous bind
ldap_client.set_option(ldap.OPT_REFERRALS,0)
ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
except ldap.INVALID_CREDENTIALS:
#print("wron")
ldap_client.unbind()
return 'Wrong username or password'
except ldap.SERVER_DOWN:
#print("down")
return 'AD server not awailable'
# all is well
# get all user groups and store it in cerrypy session for future use
ab = str(ldap_client.search_s(base_dn,
ldap.SCOPE_SUBTREE, ldap_filter, attrs)[0][1]['memberOf'])
#print("ab"+ab)
ldap_client.unbind()
return 'success'
if __name__ == "__main__":
u="chirag"
p="secred"
print(check_credentials(u,p))