Store output diskspace df -h JSON

后端 未结 4 1334
不知归路
不知归路 2021-01-07 02:34

I am attempting to gather basic disk space information from a server using a bash script, and store the output in JSON format. I am looking to record the available & use

4条回答
  •  滥情空心
    2021-01-07 03:07

    The following does what you want, with the only requirement external to bash being a Python interpreter:

    python_script=$(cat <<'EOF'
    import sys, json
    
    data = {'diskarray': []}
    for line in sys.stdin.readlines():
        mount, avail, total = line.rstrip(';').split()
        data['diskarray'].append(dict(mount=mount, spacetotal=total, spaceavail=avail))
    sys.stdout.write(json.dumps(data))
    EOF
    )
    
    df -Ph | awk '/^\// { print $1" "$2" "$3";" }' | python -c "$python_script"
    

    An alternate implementation using jq might look like this:

    df -Ph | \
      jq -R -s '
        [
          split("\n") |
          .[] |
          if test("^/") then
            gsub(" +"; " ") | split(" ") | {mount: .[0], spacetotal: .[1], spaceavail: .[2]}
          else
            empty
          end
        ]'
    

提交回复
热议问题