I retrieve members of a group and their sAMAccountName (NT Accounts) I run the following code takes from: ldap3 python search members of a group and retrieve their sAMAcountName (Active Directory)
I'm getting user name as output but after few I'm getting the error bellow:
ldap_conn.search(search_base='DC=DOMAIN,DC=com',search_filter=f'(distinguishedName={member})',attributes=['sAMAccountName'])
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/ldap3/core/connection.py", line 838, in search
request = search_operation(search_base,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/ldap3/operation/search.py", line 371, in search_operation
request['filter'] = compile_filter(parse_filter(search_filter, schema, auto_escape, auto_encode, validator, check_names).elements[0]) # parse the searchFilter string and compile it starting from the root node
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/ldap3/operation/search.py", line 214, in parse_filter
raise LDAPInvalidFilterError('malformed filter')
ldap3.core.exceptions.LDAPInvalidFilterError: malformed filter
I noticed, it failed on users who have ( ) , ? , # charters in User's Display Name(distinguishedName) , how can I filter out all non regular charters (A-Z) ?
base = "CN=mygroup,OU=Security Group,OU=Resources,OU=Global,DC=Domain,DC=com"
ldap_conn.search(search_base = base,search_filter = '(objectClass=group)',search_scope='SUBTREE',attributes = ['member'])
for entry in ldap_conn.entries:
for member in entry.member.values:
ldap_conn.search(search_base='OU=Global,DC=Domain,DC=com',search_filter=f'(distinguishedName={member})',attributes=['sAMAccountName'])
user_sAMAccountName = ldap_conn.entries[0].sAMAccountName.values
print(user_sAMAccountName)