class LDAPAPI(object):
....
def __init__(self, host, user, password, connection_timeout=10):
"""Sets up a connection to AD, ready to be queried by any
methods in the class.
"""
self.server = ldap3.Server(
host,
get_info=ldap3.ALL,
connect_timeout=connection_timeout # never let it try longer than 10 seconds
)
self.connection = ldap3.Connection(
self.server,
user=user,
password=password,
authentication=ldap3.NTLM,
auto_bind=True,
read_only=True,
check_names=True,
)
self.person_cls = ldap3.ObjectDef(['top', 'user', 'person', 'organizationalPerson'], self.connection)
def get_all_users(self, query=None):
"""
:param query: eg. query="(employeeID=1234)"
:return:
"""
log.info('Fetching all users...')
r = ldap3.Reader(self.connection, self.person_cls, self.root_folder, query)
return r.search_paged(paged_size=50)
In [2]: u = next(ldap_api.get_all_users('(employeeID=1733)'))
2020-07-31 15:39:41,620 INFO: Fetching all users...
In [3]: u.displayName
Out[3]: displayName: Test User
In [4]: u.sAMAccountName
---------------------------------------------------------------------------
LDAPCursorAttributeError Traceback (most recent call last)
<ipython-input-4-030045dc26b5> in <module>
----> 1 u.sAMAccountName
~/virtualenvs/ad/lib/python3.6/site-packages/ldap3/abstract/entry.py in __getattr__(self, item)
199 if log_enabled(ERROR):
200 log(ERROR, '%s for <%s>', error_message, self)
--> 201 raise LDAPCursorAttributeError(error_message)
202 return self._state.attributes[attr]
203 error_message = 'attribute name must be a string'
LDAPCursorAttributeError: attribute 'samaccountname' not found
试过:
r = ldap3.Reader(self.connection, self.person_cls, self.root_folder, query, attributes=['sAMAccountName'])
但出现错误:
LDAPCursorError: Attributes 'sAMAccountName' non in definition