Last active
June 26, 2018 09:44
-
-
Save approximatenumber/3317af1500e1bbaf4057392fa7b2612f to your computer and use it in GitHub Desktop.
Simple 'ldapsearch' bash wrapper for searching user info in LDAP/AD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# LDAP-server | |
host="ldap.example.org" | |
# User for auth | |
user="CN=YourUser,CN=Users,DC=ldap,DC=example,DC=org" | |
# Password of User | |
pass="YourPass" | |
# LDAP base name | |
base_name="OU=WhereToSearch,DC=ldap,DC=example,DC=org" | |
# User attributes to show | |
user_attrs="dn cn title telephoneNumber givenName distinguishedName displayName department company mail memberOf" | |
function print_help { | |
echo "Usage:" | |
echo "./$(basename $0) search <nickname>" | |
echo "./$(basename $0) info <nickname>" | |
echo "./$(basename $0) members <base_name>" | |
} | |
function search_nickname { | |
if [ ! -z $1 ]; then | |
nickname=$1 | |
found=$(ldapsearch -h $host -D $user -w $pass -b $base_name "(mailNickname=*)" mailNickname | grep $nickname | sed 's/mailNickname: //g') | |
test -z "$found" && echo "Not found" || echo $found | |
else | |
print_help | |
fi | |
} | |
function get_info { | |
if [ ! -z $1 ]; then | |
nickname=$1 | |
info=$(ldapsearch -h $host -D $user -w $pass -b $base_name "(mailNickname=$nickname)" -o ldif-wrap=no -LLL $user_attrs | \ | |
perl -MEncode -MMIME::Base64 -lpe 'if (/::/) { ($attr,$_)=split ; Encode::from_to($_=decode_base64($_),"utf8","utf8") ; $_="$attr : $_" }') | |
if [ "$info" ]; then | |
echo "$info" | |
else | |
echo "Not found" | |
exit 1 | |
fi | |
else | |
print_help | |
fi | |
} | |
function get_members { | |
if [ ! -z "$1" ]; then | |
search_path="$1" | |
ldapsearch -h $host -D $user -w $pass -b "$search_path" -o ldif-wrap=no -LLL member | \ | |
perl -MEncode -MMIME::Base64 -lpe 'if (/::/) { ($attr,$_)=split ; Encode::from_to($_=decode_base64($_),"utf8","utf8") ; $_="$attr : $_" }' | \ | |
grep -e '^dn' -e '^member' | \ | |
grep -o -e '[а-яА-Я].*' | \ | |
sort | uniq | |
else | |
print_help | |
fi | |
} | |
case $1 in | |
search) | |
search_nickname $2 | |
;; | |
info) | |
get_info $2 | |
;; | |
members) | |
get_members "$2" | |
;; | |
*) | |
print_help | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples:
search for user by nickname
get user attributes
get members of a group