-
-
Save mfominov/8d9292b6e0e1d4d95109fce496996182 to your computer and use it in GitHub Desktop.
Parse output of ldapsearch to json
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
#!/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'} | |
# inspered from https://stackoverflow.com/a/74495616/11857414 | |
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 | jq --slurp --raw-input 'split("\n\n")| | |
map(split("\n") | | |
map(select(.[0:1]!="#" and length>0)) | | |
select(length > 0) | | |
map(capture("^(?<key>[^:]*:?): *(?<value>.*)") | | |
if .key[-1:.key|length] == ":" then .key=.key[0:-1] | | |
.value=(.value|@base64d) else . end) | | |
group_by(.key) | | |
map({key:.[0].key,value:[.[].value]})| from_entries)' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment