Infinity8 Infinity8 - 1 month ago 91
Python Question

LDAP search with username as variable

I am using the Python-LDAP module and trying to make a query on the logged in user. The username will be passed into the query. When I simply type the username in as a string my results come out correctly.

But if I try to pass the (username) variable it returns

LDAPError - FILTER_ERROR: {'desc': u'Bad search filter'}
I've tried a number of different combinations but continue to get the same error returned. Any insight here would be great!

Edited for Minimal, Complete, and Verifiable example:

import ldap

LDAP_SERVER = "ldap://"
username = r"domain\serviceAccount"
password = "Password"

l = ldap.initialize(LDAP_SERVER)
def login(username, password):
l.simple_bind_s(username, password)
base = "OU=Users,OU=Group,DC=domain,DC=ad"

criteria = "(&(objectClass=user)(sAMAccountName=anActualUsername))" #WORKS
criteria = '(&(objectClass=user)(sAMAccountName=%s))' % username #DOESNT WORK
criteria = "(&(objectClass=user)" + "(sAMAccountName=" + username + "))" #DOESNT WORK

attributes = ['displayName']
result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes)
print result
return False
return True



I needed to use ldap.filter.filter_format for proper character escaping.

import ldap.filter

criteria= ldap.filter.filter_format('(&(objectClass=user)(sAMAccountName=%s))', [username])