2017-04-20 3 views
0

私は、私が必要とするようにdkpg -lコマンドからperlを使って出力の大部分を解析するPythonスクリプトを持っています。私が出力を使って何をしようとしているのは、以下のようなjson構造の出力ファイルを作成することです。私のpythonパーサースクリプトからJson出力を作成します

私は非常にPythonに新しいので、ここで私の最良のオプションは、配列構造のようなjsonファイルを生成するために何かを探していますか?

JSONファイル

{ 

"hostname": "xyz-abc-m001", 
"publicIP": "111.00.00.xxx", 
"privateIP": "10.xxx.xx.61", 
"kernal": "4.4.0-72-generiC#93-Ubuntu", 
"package": [ 
    { "name":"nfs-common", "installed":"1:1.2.8-9ubuntu12", "available":"1:1.2.8-9ubuntu12.1" }, 
    { "name":"grub-common", "installed":"2.02~beta2-36ubuntu3.8", "available":"2.02~beta2-36ubuntu3.9" }, 
    { "name":"wget", "installed":"1.17.1-1ubuntu1.1", "available":"1.17.1-1ubuntu1.2" } 

] 

} 

のPythonスクリプト

import socket 
import os 
import subprocess 
from subprocess import Popen, PIPE 


#Getting Hostname of the machine 
hostname=socket.gethostname() 

#Getting private IP of the machine on eth0 
f = os.popen(" ip addr show eth0 | grep -Po 'inet \K[\d.]+' ") 
private_ip=f.read() 

#Getting public IP of the machine on eth1 
f = os.popen(" ip addr show eth1 | grep -Po 'inet \K[\d.]+' ") 
public_ip=f.read() 

#Getting currently running linux kernal 
f = os.popen(" uname -a | awk '{print $3, $4}' ") 
running_kernal=f.read()   


pipe = Popen(" apt-get --just-print upgrade 2>&1 | perl -ne 'if (/Inst\s([\w,\-,\d,\.,~,:,\+]+)\s\[([\w,\-,\d,\.,~,:,\+]+)\]\s\(([\w,\-,\d,\.,~,:,\+]+)\)? /i) {print \"$1 $2 $3\n\"} ' ", shell=True, stdout=PIPE) 

for line in pipe.stdout: 
    parts = line.split() # split line into parts 
    if len(parts) > 1: # if at least 2 parts/columns 
     print "Hostname = %s PublicIP = %s PrivateIP = %s Package name = %s INSTALLED = %s AVAILABLE = %s kernal = %s " % (hostname, public_ip, private_ip, parts[0], parts[1], parts[2], running_kernal) 

答えて

2

そのためのライブラリがあります!

import json 

これを使用すると、データ構造を取得してjsonに変換できます。

data = [1, 2, 3, {"hello world":42}] 
myjson = json.dumps(data) 

...と基本的にはそれです。 jsonクラスとjsonファイルからそれぞれjson.loadsjson.loadをロードしてください。
詳しくは this website

P.S.インデントで印刷する場合は、

some_dictionary = {'hostname':hostname, 'PublicIP':publicIp, etc} 
print(json.dumps(some_dictionary, indent=4))` 
関連する問題