将LDAP用户导入django数据库

Joh*_*nna 9 django ldap active-directory django-auth-ldap

我想将ActiveDirectory数据库的用户导入Django.为此,我正在尝试使用django_auth_ldap模块.

这是我已经尝试过的:

在我的settings.py中:

AUTH_LDAP_SERVER_URI = "ldap://example.fr"

AUTH_LDAP_BIND_DN = 'cn=a_user,dc=example,dc=fr'
AUTH_LDAP_BIND_PASSWORD=''
AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=users,dc=example,dc=fr', ldap.SCOPE_SUBTREE, '(uid=%(user)s)')
AUTH_LDAP_GROUP_SEARCH = LDAPSearch('ou=groups,dc=example,dc=fr', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)')

AUTH_LDAP_GROUP_TYPE = ActiveDirectoryGroupType()

#Populate the Django user from the LDAP directory
AUTH_LDAP_USER_ATTR_MAP = {
    'first_name': 'sAMAccountName',
    'last_name': 'displayName',
    'email': 'mail'
}


AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)
Run Code Online (Sandbox Code Playgroud)

然后我打电话python manage.py syncdb没有结果.没有警告,没有错误,auth_user表中没有更新任何内容.有什么明显的东西我忘记了吗?

Sea*_*ira 7

查看django_auth_ldap它的文档似乎该模块实际上没有遍历LDAP用户并将它们加载到数据库中.相反,它根据LDAP对用户进行身份验证,然后使用用户登录时auth_users从LDAP获取的信息添加或更新用户.

如果要使用Active Directory中的所有用户预填充数据库,则看起来您需要编写直接查询AD并插入用户的脚本.

这样的事情应该让你开始:

import ldap

l = ldap.initialize('ldap://your_ldap_server') # or ldaps://
l.simple_bind_s("cn=a_user,dc=example,dc=fr")
users = l.search_ext_s("memberOf=YourUserGroup",\
                         ldap.SCOPE_SUBTREE, \
                         "(sAMAccountName=a_user)", \
                         attrlist=["sAMAccountName", "displayName","mail"])

# users is now an array of members who match your search criteria.
# *Each* user will look something like this:
# [["Firstname"],["LastName"],["some@email.address"]]
# Note that each field is in an array, even if there is only one value.
# If you only want the first value from each, you can transform the results:
# users = [[field[0] for field in user] for user in users]

# That will transform each row into something like this:
# ["Firstname", "Lastname", "some@email.address"]

# TODO -- add to the database.
Run Code Online (Sandbox Code Playgroud)

我已将数据库更新留给您,因为我没有关于您的设置的任何信息.

如果您需要有关LDAP查询的更多信息,请查看Stackoverflow上的LDAP问题 - 我也发现这篇文章是一个帮助.