Search code examples
bashactive-directoryldapldap-query

bash ldap search - variable as filter


I am arguing with something i expected to be simple....

I want to lookup a users manager from ldap, then get the managers email and sam name.

I expected to be able to get the cn for the manager from ldap like this:

manager=$(/usr/bin/ldapsearch -LLL -H ldap://company.ads -x -D [email protected] -w password -b ou=employees,dc=company,dc=ads sAMAccountName=employee1 | grep "manager:" | awk '{gsub("manager: ", "");print}' | awk 'BEGIN {FS=","}; {print $1, $2 }' )

that gives me the cn like this:

CN=manager,\ Surname

Now when I run another query like this:

/usr/bin/ldapsearch -LLL -H ldap://company.ads -x -D [email protected] -w password -b ou=employees,dc=company,dc=ads $manager 

I get bad search filter (-7) echo the command copy, paste run it i get the record back....

Ive tried a number of variations on this, can anyone see what im missing?

Thanks.


Solution

  • Since there's a space in $manager, you need to quote it to prevent it from being split into multiple arguments.

    /usr/bin/ldapsearch -LLL -H ldap://company.ads -x -D [email protected] -w password -b ou=employees,dc=company,dc=ads "$manager"
    

    In general, it's best to always quote your variables, unless you specifically want it to be split into words.

    You also need to remove the backslash \ from the LDAP entry. Backslashes are for escaping literal spaces in scripts, they shouldn't be used in data, because they're not processed when expanding variables.