6

Is there any way to perform a LDAP search and save the results into a table format (e.g. csv)?

Cheers Jorge

jorgehumberto
  • 1,047
  • 5
  • 15
  • 33

3 Answers3

9

You can use the excellent miller tool (mlr)

The last bit:

echo output | sed 's/://g'  | mlr --x2c cat then unsparsify

How it works:

  • the sed converts the output to XTAB format
  • --x2c converts XTAB to CSV
  • cat then unsparsify makes sure the missing values are just filled instead of breaking to different csv output

Total command:

ldapsearch -H ldap://<hostname>:389 -D "<bindDN>" -W -b "<base>" '<query>' -oldif-wrap=no -LLL cn mail telephoneNumber | sed 's/://g'  | mlr --x2c cat then unsparsify
Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
  • This sort of works for me, but 1) don't need that `sed` and 2) `openldap` doesn't return fields in a consistent order. What works for me is run a query that would generate an expected list of a single attribute, then import and inspect that list, and run additional queries for alternate lists. Example: `ldapsearch -x '(&(uidNumber>=2000)(loginShell=/usr/sbin/nologin))' gecos | mlr --x2c cat # list disabled users by full name` – dannyman Jan 18 '23 at 22:20
6

Just in case someone else has to do this:

Based on the answer provided in Filter ldapsearch with awk/bash

this will output the LDAP info into a csv format:

$ ldapsearch -x -D "cn=something" | awk -v OFS=',' '{split($0,a,": ")} /^mail:/{mail=a[2]} /^uidNumber:/{uidNumber=a[2]} /^uid:/{uid=a[2]} /^cn/{cn=a[2]; print uid, uidNumber,cn , mail}' > ldap_dump.csv

NOTE You need to be careful about the order in which you parse the LDAP data with awk! It needs to be parsed in the same order as it appears on the LDAP data!

jorgehumberto
  • 1,047
  • 5
  • 15
  • 33
0

If you have the list of the attributes you want in column you could do something like this

attributes=("$@") # e.g.("uid" "mail")
separator=','
quote='"'
ldapSearch <options> <filter> "${attributes[@]}" | \
  while read dn; do
    # read attributes below dn until an empty line is found
    while read attribute && [[ -n "$attribute" ]]; do
      # split name and value and assign the value to a variable named after the attribute name
      name="$(awk -F ': ' '{print $1}' <<< "$attribute")"
      value="$(awk -F ': ' '{print $2}' <<< "$attribute")"
      printf -v "$name" '%s' "$value"
    done
    # print quoted dn followed by ordered list of attribute values using indirect expansion
    echo -n "${quote}${dn#dn: }${quote}"
    for attribute in "${attributes[@]}"; do
      echo -n "${separator}${quote}${!attribute}${quote}"
    done
    echo
  done
dgaffuri
  • 36
  • 4