简体   繁体   English

bash输出为json格式

[英]bash output to json format

I'm new to Linux and Bash scripting.我是 Linux 和 Bash 脚本的新手。 I am trying to output several bash scripts in Ubuntu Linux into JSON format, however, I cannot seem to get it to work properly.我正在尝试将 Ubuntu Linux 中的几个 bash 脚本输出为 JSON 格式,但是,我似乎无法让它正常工作。

My goal is to get this:我的目标是得到这个:

date -u +%Y-%m-%d:%H:%M:%S  //date and time

lsb_release -a  //os distro version

ifconfig -a  //ip info

Into this format in JSON:转换成 JSON 格式:

  "datetime":datetime_string,

  "osversion":string,

  "ip_info:  [{"interface":string,"ip_addr":string,"mask":string,"gateway":string},
             {"interface":string,"ip_addr":string,"mask":string,"gateway":string}],

使用jo应该很容易做到这样的事情:

jo datetime=$(date -u +%Y-%m-%d:%H:%M:%S) osversion=$(lsb_release -a) ip_info=$(jo -a $(ip -o addr list))

Bash itself has no JSON support. Bash 本身不支持 JSON。 Thus, to guarantee conformance, you need to use an external utility with JSON parsing and generation support built in. jq is one of these, and the below uses its built-in regex support:因此,为了保证一致性,您需要使用内置 JSON 解析和生成支持的外部实用程序。 jq是其中之一,以下使用其内置的正则表达式支持:

jq --raw-input \
   --arg date "$(date)" \
   --arg osver "$(lsb_release -a)" \
   '{"date": $date,
     "osver": $osver,
     "ip_info": [inputs |
                 capture("^[0-9]+: (?<ifname>[^[:space:]]+)[[:space:]]+inet (?<addr>[^[:space:]/]+)(/(?<masklen>[[:digit:]]+))?")
                ]
    }' \
   < <(ip -o addr list | grep 'inet ')

See this code in action on JQPlay . 在 JQPlay 上查看此代码。


If you can't install tools not built into your Linux distro, consider Python:如果您无法安装 Linux 发行版中未内置的工具,请考虑使用 Python:

#!/bin/bash
#      ^^^^ - important, not /bin/sh; this uses some bash-only syntax

py_code=$(cat <<'EOF'
import json, re, sys

content={'ip_info': []}
for k, v in [ arg.split('=', 1) for arg in sys.argv[2:] if '=' in arg ]:
  content[k]=v

ip_re = re.compile(r'^[0-9]+:\s+(?P<ifname>\S+)\s+inet (?P<addr>[^/\s]+)(?:/(?P<masklen>\d+))?')
for line in open(sys.argv[1]).readlines():
  m = ip_re.match(line)
  if not m: raise "NOOOO"
  content['ip_info'].append({
    'ifname': m.groups('ifname'),
    'addr': m.groups('addr'),
    'masklen': m.groups('masklen'),
  })

print json.dumps(content)
EOF
)

python -c "$py_code" \
  <(ip -o addr list | grep 'inet ') \
  "date=$(date)" "osver=$(lsb_release -a)"

I created a tool called jc that converts the output of many command line tools, including ifconfig , to json: 我创建了一个名为jc的工具,该工具将许多命令行工具(包括ifconfig的输出转换为json:

https://github.com/kellyjonbrazil/jc https://github.com/kellyjonbrazil/jc

$ ifconfig | jc --ifconfig -p
[
  {
    "name": "docker0",
    "flags": "4099",
    "state": "UP,BROADCAST,MULTICAST",
    "mtu": "1500",
    "ipv4_addr": "172.17.0.1",
    "ipv4_mask": "255.255.0.0",
    "ipv4_bcast": "0.0.0.0",
    "mac_addr": "02:42:53:18:31:cc",
    "type": "Ethernet",
    "rx_packets": "0",
    "rx_errors": "0",
    "rx_dropped": "0",
    "rx_overruns": "0",
    "rx_frame": "0",
    "tx_packets": "0",
    "tx_errors": "0",
    "tx_dropped": "0",
    "tx_overruns": "0",
    "tx_carrier": "0",
    "tx_collisions": "0",
    "ipv6_addr": null,
    "ipv6_mask": null,
    "ipv6_scope": null,
    "metric": null
  },
  {
    "name": "ens33",
    "flags": "4163",
    "state": "UP,BROADCAST,RUNNING,MULTICAST",
    "mtu": "1500",
    "ipv4_addr": "192.168.71.135",
    "ipv4_mask": "255.255.255.0",
    "ipv4_bcast": "192.168.71.255",
    "ipv6_addr": "fe80::c1cb:715d:bc3e:b8a0",
    "ipv6_mask": "64",
    "ipv6_scope": "link",
    "mac_addr": "00:0c:29:3b:58:0e",
    "type": "Ethernet",
    "rx_packets": "26348",
    "rx_errors": "0",
    "rx_dropped": "0",
    "rx_overruns": "0",
    "rx_frame": "0",
    "tx_packets": "5308",
    "tx_errors": "0",
    "tx_dropped": "0",
    "tx_overruns": "0",
    "tx_carrier": "0",
    "tx_collisions": "0",
    "metric": null
  },
  {
    "name": "lo",
    "flags": "73",
    "state": "UP,LOOPBACK,RUNNING",
    "mtu": "65536",
    "ipv4_addr": "127.0.0.1",
    "ipv4_mask": "255.0.0.0",
    "ipv4_bcast": null,
    "ipv6_addr": "::1",
    "ipv6_mask": "128",
    "ipv6_scope": "host",
    "mac_addr": null,
    "type": "Local Loopback",
    "rx_packets": "64",
    "rx_errors": "0",
    "rx_dropped": "0",
    "rx_overruns": "0",
    "rx_frame": "0",
    "tx_packets": "64",
    "tx_errors": "0",
    "tx_dropped": "0",
    "tx_overruns": "0",
    "tx_carrier": "0",
    "tx_collisions": "0",
    "metric": null
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM