금요일, 1월 17, 2025
HomeLanguageLinux CPU, RAM, HDD 정보를 JSON문자열 가져오기

Linux CPU, RAM, HDD 정보를 JSON문자열 가져오기

Linux CPU, RAM, HDD 정보를 JSON문자열 가져오기

1.cpuinfo.py

import os

cpuinfo =str(os.popen('top -bn2 | grep \"Cpu(s)\" | awk \'NR>1{printf \"{ \\"used\\": \\"%.1f\\",\\"free\\": \\"%.1f\\"}\", $2,$5 }\'').readline())

print(cpuinfo)

2.meminfo.py

import os

cpuinfo =str(os.popen('free -m | awk \'NR==2{printf \"{ \\"used\\":%d, \\"free\\": \\"%d\\" }\", $3,$4 }\'').readline())

print(cpuinfo)

3.df.py

# df.py
#
# parse the output of df and create JSON objects for each filesystem.
#
# $Id: df.py,v 1.5 2014/09/03 00:41:31 marc Exp $
#

# now let's parse the output of df to get filesystem information
#
# Filesystem                1K-blocks    Used Available Use% Mounted on
# /dev/mapper/flapjack-root 959088096 3799548 906569700   1% /
# udev                        1011376       4   1011372   1% /dev
# tmpfs                        204092     288    203804   1% /run
# none                           5120       0      5120   0% /run/lock
# none                        1020452       0   1020452   0% /run/shm
# /dev/sda1                    233191   50734    170016  23% /boot

import subprocess
import shlex
import json

def main():
    """Main routine - call the df utility and return a json structure."""

    # this next line of code is pretty tense ... let me explain what
    # it does:
    # subprocess.check_output(["df"]) runs the df command and returns
    #     the output as a string
    # rstrip() trims of the last whitespace character, which is a '\n'
    # split('\n') breaks the string at the newline characters ... the
    #     result is an array of strings
    # the list comprehension then applies shlex.split() to each string,
    #     breaking each into tokens
    # when we're done, we have a two-dimensional array with rows of
    # tokens and we're ready to make objects out of them
    df_array = [shlex.split(x) for x in
                subprocess.check_output(["df"]).rstrip().split('\n')]
    df_num_lines = df_array[:].__len__()

    df_json = {}
    df_json = []
    for row in range(1, df_num_lines):
        df_json.append(df_to_json(df_array[row]))
    print json.dumps(df_json, sort_keys=True, indent=2)
    return

def df_to_json(tokenList):
    """Take a list of tokens from df and return a python object."""
    # If df's ouput format changes, we'll be in trouble, of course.
    # the 0 token is the name of the filesystem
    # the 1 token is the size of the filesystem in 1K blocks
    # the 2 token is the amount used of the filesystem
    # the 5 token is the mount point
    result = {}
    fsName = tokenList[0]
    fsSize = tokenList[1]
    fsUsed = tokenList[2]
    fsAvail= tokenList[3]
    fsMountPoint = tokenList[5]
    result["filesystem"] = {}
    result["filesystem"]["name"] = fsName
    result["filesystem"]["total_size"] = fsSize
    result["filesystem"]["used"] = fsUsed
    result["filesystem"]["avail"] = fsAvail
    result["filesystem"]["mount_point"] = fsMountPoint
    return result

if __name__ == '__main__':
    main()

4.sysinfo.sh

#!/bin/bash

target=/tmp/svrinfo.txt

rm -f $target
echo "{" >> $target
echo '"cpu":"'$(/usr/bin/python /sw/script/cpuinfo.py)'",' >> $target
echo '"mem":"'$(/usr/bin/python /sw/script/meminfo.py)'",' >> $target
echo '"hdd":"'$(/usr/bin/python /sw/script/df.py)'"' >> $target
echo '}' >> $target

echo $(cat $target)

5.hdd 정보를 가져오는 df.py 버전문제로 인하여 안될시

#!/bin/bash

target=/tmp/svrinfo.txt

HDDINFO=$(df |grep "/sw"|awk '{printf "{\"mount_point\": \"%s\", \"total_size\": \"%d\", \"used\": \"%d\", \"free\": \"%d\"},", $5,$1,$2,$3}';df |grep "/dev/sda2"|awk '{printf "{\"mount_point\": \"%s\", \"total_size\": \"%d\", \"used\": \"%d\", \"free\": \"%d\"}", $6,$2,$3,$4}')
rm -f $target
echo "{" >> $target
echo '"cpu":"'$(/usr/bin/python /sw/script/cpuinfo.py)'",' >> $target
echo '"mem":"'$(/usr/bin/python /sw/script/meminfo.py)'",' >> $target
echo '"hdd":['$HDDINFO']' >> $target
echo '}' >> $target

echo $(cat $target)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular