Multi Stage LDAP Searches With Awk


Problem: query LDAP for all users in a particular group, when LDAP is set up in POSIX style (memberUID: in each group record instead of memberOf: in each user record) without writing a script.

Finding the members from the group is fairly easy:

$ ldapsearch -x -b dc=computecanada,dc=ca cn=grpname
# extended LDIF
#
# LDAPv3
# base <dc=computecanada,dc=ca> with scope subtree
# filter: cn=grpname
# requesting: ALL
#

# grpname, Group, computecanada.ca
dn: cn=grpname,ou=Group,dc=computecanada,dc=ca
cn: grpname
objectClass: posixGroup
gidNumber: 1234567
memberUid: user1
memberUid: user2
memberUid: user3

# search result
search: 2
result: 0 Success

# numResponses: 2
# numEntries: 1

Next, print only the usernames (here using printf to avoid newlines) by selecting only the memberUid lines with awk:

$ ldapsearch -x -b dc=computecanada,dc=ca cn=grpname | \
  awk '$1 == "memberUid:" { printf($2) }'
user1user2user3

Now a more complex output, generating an LDAP search filter expression, in this case an OR expression matching any of the usernames:

$ ldapsearch -x -b dc=computecanada,dc=ca cn=grpname | \
  awk 'BEGIN{printf("(|")} $1 == "memberUid:" {printf("(uid="$2")")} END{printf(")")}'
(|(uid=users1)(uid=user2)(uid=user3))

Finally, use that expression as the query for a second LDAP search:

ldapsearch -x -b dc=computecanada,dc=ca $( \
  ldapsearch -x -b dc=computecanada,dc=ca cn=grpname | \
    awk 'BEGIN{printf("(|")} $1 == "memberUid:" {printf("(uid="$2")")} END{printf(")")}' \
  )
awk  noscript  ldap 

See also