2016-05-06 57 views
1

我目前有一個使用MySQL後端的應用程序,並且我有一個客戶端,它擁有存儲在其上的用戶的配置文件信息,但他們也有Active Directory,並且想知道我是否可以來自那裏的信息以及從那裏檢索特定配置文件的信息。我知道你可以爲多個SQL數據庫連接配置Django,或者將身份驗證後端替換爲Active Directory。在Django中從外部Active Directory中提取數據

https://docs.djangoproject.com/en/1.9/topics/db/multi-db/

https://pythonhosted.org/django-auth-ldap/

但我在想,如果我能在同一時間做MySQL和Active Directory或做我只需要連接到Active Directory外部和檢索信息的方式?

這是可行的嗎?如果是的話,哪種方法最好?

+0

您可以編寫管理命令,將存儲在數據庫中的配置文件與Active Directory中的數據同步。或認證後端將做到這一點。或兩者。 –

回答

1

我與我管理的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) 
+1

是的,我只需要拉取數據並將其顯示在視圖中。而已。 – nastyn8

相關問題