Querying AD Group Membership Status With ldapsearch



Here’s a way to query Active Directory for group membership status with the ldapsearch utility. In my case, this was used to check if a user is authorized before attempting to mount an SMB share at login on OS X clients. The -Q option causes ldapsearch to use SASL quiet mode and not prompt for a password, which works if a Kerberos ticket is present.

#!/bin/bash

console_user="$(/usr/bin/stat -f%Su /dev/console)"
ldap_uri="ldap://example.com"
search_base="DC=example,DC=com"
group="Some Group"
is_member_of_group=`/usr/bin/ldapsearch -LLL -Q -H "$ldap_uri" -b "$search_base" "sAMAccountName=$console_user" sAMAccountName | $grep "OU=$group"` # -Q prevents the authentication prompt, works if kerberos ticket exists

if [[ "${#is_member_of_group}" -ne "0" ]]; then
    echo "$console_user is a member of $group."
    # Do something about it
else
    echo "$console_user is NOT a member of $group."
    # Do something else
fi

exit $?
comments powered by Disqus