我與我管理的Django站點有類似的情況。這裏的Django應用程序使用:
https://github.com/etianen/django-python3-ldap
它讓我使用PostgreSQL爲我的數據庫,我拉出來需要的Active Directory和成字段映射用戶記錄用戶的元數據。這是我幾次錯誤發現後找到的最好方法。
如果你只是希望從Active Directory中提取數據,而不是到Django的用戶,這裏的包和一個代碼示例我發現工作:
的Python 3包:混帳+ https://github.com/rbarrois/[email protected]
實例,您可以修改與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/[email protected]
"""
import ldap
LDAP_URI = 'ldap://ldap.server.com'
LDAP_DN = 'dc=server,dc=com'
LDAP_USERNAME = '[email protected]'
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)
這兩條線路連接到Active Directory使用LDAP包時是必不可少的
ldap_con.protocol_version = 3
ldap_con.set_option(ldap.OPT_REFERRALS, 0)
您可以編寫管理命令,將存儲在數據庫中的配置文件與Active Directory中的數據同步。或認證後端將做到這一點。或兩者。 –