请求:使用jq将LDAP查询输出转换为指定JSON格式(支持管道输入)
用jq将LDAP搜索输出转换为指定格式JSON(支持标准输入/管道)
没问题!我经常处理这类需求,下面就给你详细讲怎么用jq实现,完全适配从管道或者标准输入接收LDAP数据的场景。
先明确前提
通常咱们用ldapsearch工具查出来的默认输出是LDIF格式(LDAP Data Interchange Format),所以下面的方案主要针对这种最常见的情况来做。如果你的LDAP输出是其他格式,可以随时调整~
基础版:把LDIF转成通用JSON数组
如果只是想把每个LDAP条目转成JSON对象,再拼成一个数组,用这个jq脚本就够了:
ldapsearch -x -b "dc=example,dc=com" "(objectClass=user)" | jq -n ' reduce inputs as $line ( { current: null, result: [] }; if $line | test("^dn:") then if .current != null then .result += [.current] end; { current: { dn: $line | sub("^dn: "; "") }, result: .result } elif $line | test("^\\s") then .current[last_key] += " " + ($line | sub("^\\s+"; "")) elif $line != "" then ($line | split(": "; 2)) as [$key, $value] | .current[$key] = $value | .last_key = $key else . ) | .result += [.current] | .result '
脚本逻辑拆解
-n参数:让jq不要自动读取输入,而是咱们手动用reduce逐行处理,更灵活- 用
reduce维护两个状态:current是正在构建的当前LDAP条目,result是最终的结果数组 - 遇到
dn:开头的行:先把之前的current塞进结果数组,然后初始化新的条目 - 遇到缩进的行:这是LDIF里的多行属性值,把内容追加到上一个属性里
- 遇到非空非缩进的行:分割成键值对,添加到当前条目里
- 最后把最后一个条目也加入数组,输出最终结果
自定义指定JSON格式
如果需要输出特定字段的JSON(比如只保留dn、cn、mail,还想自定义字段名),只需要在脚本最后加个字段映射就行,修改后的脚本如下:
ldapsearch -x -b "dc=example,dc=com" "(objectClass=user)" | jq -n ' reduce inputs as $line ( { current: null, result: [] }; if $line | test("^dn:") then if .current != null then .result += [.current] end; { current: { dn: $line | sub("^dn: "; "") }, result: .result } elif $line | test("^\\s") then .current[last_key] += " " + ($line | sub("^\\s+"; "")) elif $line != "" then ($line | split(": "; 2)) as [$key, $value] | .current[$key] = $value | .last_key = $key else . ) | .result += [.current] | .result | map({ distinguished_name: .dn, full_name: .cn, email: .mail }) '
这样输出的每个JSON对象就只有你指定的字段,字段名也可以随便改,完全贴合你的需求。
灵活的输入方式
不管你的LDAP输出是直接从ldapsearch管道过来,还是已经存在文件里,都能适配:
# 从文件读取输入 jq -n '...' < ldap_output.ldif # 或者用管道传递 cat ldap_output.ldif | jq -n '...'
小提醒
- 如果属性值里有冒号,
split(": "; 2)会只分割第一个:,避免把值里的冒号当成分隔符 - 要是遇到二进制属性(比如
jpegPhoto),LDIF里是base64编码的,你可以用jq的@base64d过滤器解码,比如.photo = .jpegPhoto | @base64d
内容的提问来源于stack exchange,提问作者Jorixine
相关产品推荐
相关产品推荐

