3

我对 AD 和 LDAP 了解不多,但是尝试用 Python 实现最简单的 LDAP/AD 登录功能。到目前为止,虽然我测试了几个不同的模块,但运气不错。最有希望的可能是ldap3

>>> import ldap3
>>> server = ldap3.Server('myserver')
>>> connection = ldap3.Connection(server)
>>> connection.bind()
True
>>> connection.search(search_base='DC=mydomain,DC=com', search_filter='(&(objectClass=person)(userPrincipalName=firstname.lastname@mydomain.com))', search_scope='LEVEL', attributes=ldap3.ALL_ATTRIBUTES)
True
>>> connection.response[0]
{'uri': ['ldap://ForestDnsZones.mydomain.com/DC=ForestDnsZones,DC=mydomain,DC=com??base'], 'type': 'searchResRef'}
>>> connection.result
{'result': 0, 'description': 'success', 'dn': '', 'message': '', 'referrals': None, 'type': 'searchResDone'}

如果这在正确的道路上,你能给我一些指示吗?

该设置似乎足以满足基础知识,因为我能够从中提取某种类型的元数据:

>>> server._get_dsa_info(connection)
>>> server._dsa_info
DSA info (from DSE):
  Supported LDAP versions: 3, 2
  Naming contexts:
    DC=mydomain,DC=com
    CN=Configuration,DC=mydomain,DC=com
    CN=Schema,CN=Configuration,DC=mydomain,DC=com
    DC=DomainDnsZones,DC=mydomain,DC=com
    DC=ForestDnsZones,DC=mydomain,DC=com

  Supported controls:
    1.2.840.113556.1.4.1338 - Verify name - Control - MICROSOFT
    1.2.840.113556.1.4.1339 - Domain scope - Control - MICROSOFT
    1.2.840.113556.1.4.1340 - Search options - Control - MICROSOFT
    ...

我也尝试过flask-ldap3-login,但开始怀疑我们的 AD 没有按照标准配置,因为我得到了:

...
>>> response = ldap_manager.authenticate('me', 'my_pass')
LDAPNoSuchObjectResult - 32 - noSuchObject - CN=Schema,CN=Configuration,DC=mydomain,DC=com - 0000208D: NameErr: DSID-0315270B, problem 2001 (NO_OBJECT), data 0, best match of:
        'CN=Schema,CN=Configuration,DC=mydomain,DC=com'
  - searchResDone - None

请不要犹豫,询问更多信息,我会尽力弄清楚。例如,我自己的用户位于:

CN=Lastname Firstname,OU=Consultants,OU=Users,OU=SE,OU=MYDOMAIN,DC=mydomain,DC=com

一些值是:

objectClass = top;person;organizationalPerson;user
name = Lastname Firstname
userPrincipalName = Firstname.Lastname@mydomain.com

此外,CN=Schema,CN=Configuration,DC=mydomain,DC=com只有一个子模式,CN=Aggregate,CN=Schema,CN=Configuration,DC=mydomain,DC=com它看起来是空的。出于某种原因,我相信这是 flask-ldap3-login 尝试使用的。

4

1 回答 1

4

我使用的问题ldap3.Connection是我在绑定时没有使用登录。这似乎是一个前进的方向:

import ldap3
user = 'me@mycompany.com'
password = 'mypassword'
server = ldap3.Server('myserver')
connection = ldap3.Connection(server, user=user, password=password)
connection.bind()
connection.search(search_base='DC=mycompany,DC=com', search_filter='(&(objectClass=user)(userPrincipalName='+user+'))', search_scope='SUBTREE', attributes='*')

如果你想打印一些数据:

attrs = connection.response[0]['attributes']
print(attrs['displayName'])
for memb in attrs['memberOf']:
    print(memb.partition('=')[2].partition(',')[0])
于 2017-11-15T14:29:44.860 回答