Search code examples
pythonpython-ldap

Bad search filter


Im trying to filter few attributes from the ldap server but get errors,

ldap.FILTER_ERROR: {'desc': 'Bad search filter'}

Code:-

import ldap
ldap.OPT_REFERRALS = 0

ldap_server="ldapps.test.com"
username = "testuser"
password= "" #your password
connect = ldap.open(ldap_server)

dn='uid='+username;
print 'dn =', dn
try:
    result = connect.simple_bind_s(username,password)
    print 'connected == ', result
    filter1 = "(|(uid=" + username + "\*))"
    result = connect.search("DC=cable,DC=com,DC=com",ldap.SCOPE_SUBTREE,filter1)
    print result

except ldap.INVALID_CREDENTIALS as e:
    connect.unbind_s()
    print "authentication error == ", e

Solution

  • Your search filter is, in fact, bad.

    The | character is for joining several conditions together in an OR statement. For example, if you wanted to find people with a last name of "smith", "jones", or "baker", you would use this filter:

    (|(lastname=smith)(lastname=jones)(lastname=baker))
    

    However, your filter only has one condition, so there's nothing for the | character to join together. Change your filter to this and it should work:

    "(uid=" + username + "\*)"
    

    By the way, what are you trying to do with the backslash and asterisk? Are you looking for people whose usernames actually end with an asterisk?