LDAPSEARCH 为表格格式

问题描述 投票:0回答:4

有没有办法执行 LDAP 搜索并将结果保存为表格格式(例如 csv)?

干杯 豪尔赫

ldap openldap ldap-query
4个回答
9
投票

您可以使用优秀的铣床工具(

mlr
)

最后一点:

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

工作原理:

  • sed 将输出转换为
    XTAB
    格式
  • --x2c
    XTAB
    转换为
    CSV
  • cat
    然后
    unsparsify
    确保缺失值被填充,而不是中断到不同的 csv 输出

总指挥:

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

6
投票

以防万一其他人必须这样做:

根据中提供的答案 使用 awk/bash 过滤 ldapsearch

这会将 LDAP 信息输出为 csv 格式:

$ 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

注意 您需要注意使用 awk 解析 LDAP 数据的顺序!它需要按照 LDAP 数据上显示的顺序进行解析!


0
投票

如果您在列中有所需属性的列表,您可以执行类似的操作

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

0
投票

将@rob-audenarde的答案与@sebastian-stark和@dannyman的评论相结合,以及https://unix.stackexchange.com/a/735968 我想出了这个:

ldapsearch -ZxLLL \
  | perl -MMIME::Base64 -pe 's/^((?:[^:]*)):: *(.*)/"$1: " . decode_base64($2)/e' \
  | mlr --x2c -N cut -f uid:,sn:,givenName: -o

这将始终首先输出姓氏,最后输出给定名称,与 ldapsearch 中的顺序无关。 @jorgehumberto 的变体不起作用,因为编辑属性时 ldapsearch 的输出顺序会发生变化,更改后的属性将始终附加到列表中。

输出顺序(实际上还有要显示的属性的过滤器)是在工具 miller (mlr) 中使用子命令

cut
:

完成的
  • --x2c
    ### 将 tab 转换为 css
  • cut
    ### 从输出中切下一些片段
    • -f field1,field2,...
      ### 仅使用指定字段
    • -o
      ### 使用上面 -f 指定的输出顺序

Perl 单行代码仅修改带有

::
的行,并使用 perl 内部decode_base64 解码第二部分。这里要小心一点:如果该行很长并且 ldapsearch 包装了输出,那么此片段还没有涵盖这一点。 (LDIF 延续行在第一个位置以空格开头,需要附加到上一行...)

© www.soinside.com 2019 - 2024. All rights reserved.