存储输出磁盘空间df -h JSON [英] Store output diskspace df -h JSON

查看:85
本文介绍了存储输出磁盘空间df -h JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用bash脚本从服务器收集基本磁盘空间信息,并以JSON格式存储输出.我希望记录可用的&使用的磁盘空间.

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 & used disk space.

df -h的示例输出:

An example output of df -h:

Filesystem                      Size  Used Avail Use% Mounted on
udev                            2.0G  4.0K  2.0G   1% /dev
tmpfs                           394M  288K  394M   1% /run
/dev/mapper/nodequery--vg-root   45G  1.4G   41G   4% /
none                            4.0K     0  4.0K   0% /sys/fs/cgroup
none                            5.0M     0  5.0M   0% /run/lock
none                            2.0G     0  2.0G   0% /run/shm
none                            100M     0  100M   0% /run/user
/dev/sda2                       237M   47M  178M  21% /boot
/dev/sda1                       511M  3.4M  508M   1% /boot/efi

作为一个例子,这就是我希望最终输出看起来的样子.

As an example this is how I would like the final output to look.

{
  "diskarray": [{
    "mount": "/dev/disk1",
    "spacetotal": "35GB",
    "spaceavail": "1GB"
  },
  {
    "mount": "/dev/disk2",
    "spacetotal": "35GB",
    "spaceavail": "4GB"
  }]
}

到目前为止,我已经尝试使用awk:

So far I've tried using awk:

df -P -B 1 | grep '^/' | awk '{ print $1" "$2" "$3";" }'

具有以下输出:

/dev/mapper/nodequery--vg-root 47710605312 1439592448;
/dev/sda2 247772160 48645120;
/dev/sda1 535805952 3538944;

但是我不确定如何获取这些数据并将其以JSON格式存储.

But I'm not sure how I take that data and store it in the JSON format.

推荐答案

以下是您想要的,bash外部唯一的要求是Python解释器:

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"

使用 jq 的替代实现可能看起来像这样:

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
    ]'

这篇关于存储输出磁盘空间df -h JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆