-1

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 responses 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

it failed once try to retrieve user who have ( ) , ? , # , é charters in CN, how can escape to avoid from malformed filter error ?

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)
General Grievance
  • 4,555
  • 31
  • 31
  • 45
shlco
  • 1
  • 2
  • You need to use [`ldap.filter.escape_filter_chars()`](https://www.python-ldap.org/en/python-ldap-3.3.0/reference/ldap-filter.html). See this [post](https://stackoverflow.com/a/39805523/2529954) for more details. – EricLavault Feb 26 '23 at 13:16

1 Answers1

-2

Depending on the LDAP client module (you seem to be using ldap3):

  • For ldap3, use ldap3.utils.conv.escape_filter_chars(member).
  • For python-ldap, use ldap.filter.escape_filter_chars(member).
user1686
  • 13,155
  • 2
  • 35
  • 54