Skip to content

Instantly share code, notes, and snippets.

@jforge
Forked from deardooley/ldap2json.sh
Created May 30, 2023 09:49
Show Gist options
  • Select an option

  • Save jforge/d9126f043115de1edc079e480fc303b3 to your computer and use it in GitHub Desktop.

Select an option

Save jforge/d9126f043115de1edc079e480fc303b3 to your computer and use it in GitHub Desktop.
Parse output of ldapsearch to json
#!/usr/bin/env bash
# ldap2json.sh
#
# Example shell script showing how to parse LDIF output from the
# ldapsearch command into a json array. Please note that this
# script almost certainly does not handle every edge case, and
# is best used to pull a handful of fields a user or group
# record in a FreeIPA ldap server and format them as JSON for use
# in other tools.
#
LDAP_SEARCH_BIND_DN=${LDAP_SEARCH_BIND_DN:-'uid=readonly,dc=ipa,dc=example,dc=com'}
LDAP_SEARCH_BIND_PASS=${LDAP_SEARCH_BIND_PASS:-'password'}
LDAP_SEARCH_BASE=${LDAP_SEARCH_BASE:-'cn=users,dc=ipa,dc=example,dc=com'}
LDAP_SEARCH_HOST=${LDAP_SEARCH_HOST:-'ldap://ldap.ipa.example.com'}
LDAP_SEARCH_FILTER=${LDAP_SEARCH_FILTER:-'memberOf=cn=staff'}
LDAP_SEARCH_FIELDS=${LDAP_SEARCH_FIELDS:-'cn displayName mail uid'}
# Formats output from ldif format into a json structure containing the
# LDAP_SEARCH_FIELDS as keys.
# Note:
# - Repeated keys overwrite each other
# - uuid is used as a entry delimiter and will always be appended as the
# field provided in the ldapsearch request
function ldif_to_json () {
echo $(echo -e "${1}" | \
sed -E 's/(.*)\: (.*)/"\1": "\2",/g' | \
sed -E 's/"ssh\-rsa (.*) (.*)$/"ssh-rsa \1",/g' | \
sed -E 's/^"dn(.*)$/{"dn\1/g' | \
sed -E 's/^"uid(.*)",$/"uid\1"},/g' ) | \
sed -E 's/(.*),$/[\1]/'
}
# Make the call to ldapsearch and send to the ldif_to_json
# function for formatting
ldif_to_json "$( ldapsearch -LLL -B -o ldif-wrap=no -x \
-w "$LDAP_SEARCH_BIND_PASS" \
-b "$LDAP_SEARCH_BASE" \
-D "$LDAP_SEARCH_BIND_DN" \
-H "$LDAP_SEARCH_HOST" \
$LDAP_SEARCH_FILTER \
$LDAP_SEARCH_FIELDS )"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment