我管理的一个 Django 站点也有类似的情况。这是我使用的 Django 应用程序:
https://github.com/etianen/django-python3-ldap
它允许我将 PostgreSQL 用于我的数据库,并通过映射字段将我需要的用户元数据从 Active Directory 中提取到用户记录中。这是我在几次错误开始后找到的最好的方法。
如果您只是想从 Active Directory 中提取数据而不是向 Django 用户中提取数据,这里是我发现可以工作的包和代码示例:
Python 3 包:git+https://github.com/rbarrois/python-ldap.git@py3
示例,您可以对其进行修改以使用 Django 的 ORM:
"""
This code provide an example of how to connect to LDAP (specifically, Active Directory)
using Python 3.
Requires python-ldap3, available via the following command:
pip install git+https://github.com/rbarrois/python-ldap.git@py3
"""
import ldap
LDAP_URI = 'ldap://ldap.server.com'
LDAP_DN = 'dc=server,dc=com'
LDAP_USERNAME = 'ldap_user@server.com'
LDAP_PASSWORD = ''
USER_NAME = 'username-to-test'
USER_IN_GROUP = 'CN=SomeGroup,DC=server,DC=com'
USER_NOT_IN_GROUP = 'CN=SomeGroupThatDoesNotExist,DC=server,DC=com'
try:
# Connect to LDAP / Active Directory
ldap_con = ldap.initialize(LDAP_URI)
ldap_con.protocol_version = 3
ldap_con.set_option(ldap.OPT_REFERRALS, 0)
ldap_con.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
# sAMAAccountName is Active Directory's 'username'
user_filter='(&(objectCategory=person)(objectClass=user)(sAMAccountName=' + USER_NAME + '))'
attrs = ['memberOf']
# Perform the search.
ldap_user = ldap_con.search_s(LDAP_DN, ldap.SCOPE_SUBTREE, user_filter, attrs)
# Active Directory returns a list of byte literals. Convert them to strings in a more sensibly named list.
ldap_groups = []
for value in ldap_user[0][1]['memberOf']:
ldap_groups.append(value.decode('utf-8'))
# Print the LDAP groups the user above is a member of, one per line.
for value in ldap_groups:
print(value)
# Perform check to see whether a user is in a group, or explicitly, a user it not in a group.
if USER_IN_GROUP in ldap_groups:
print(USER_NAME + " is a member of " + USER_IN_GROUP)
else:
print(USER_NAME + " is not a member of " + USER_IN_GROUP)
if USER_NOT_IN_GROUP in ldap_groups:
print(USER_NAME + " is a member of " + USER_NOT_IN_GROUP)
else:
print(USER_NAME + " is not a member of " + USER_NOT_IN_GROUP)
# Unbind from LDAP / Active Directory.
ldap_con.unbind()
except ldap.LDAPError:
print(ldap.LDAPError)
在使用 LDAP 包连接到 Active Directory 时,这两行是必不可少的:
ldap_con.protocol_version = 3
ldap_con.set_option(ldap.OPT_REFERRALS, 0)