对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 试图使用的。
请您参考如下方法:
我在使用 ldap3.Connection 时遇到的问题是我在绑定(bind)时没有使用登录。这似乎是一个前进的方向:
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])
