[英]Create Json output from my python parser script
I have a python script that I wrote in which I parse most of the output using perl from dkpg -l command as per my need. 我有一个编写的python脚本,其中我根据需要使用dkpg -l命令的perl解析大部分输出。 What i am trying to do with the output is to create a json structure output file like below. 我想对输出进行的操作是创建一个json结构输出文件,如下所示。
I am very new to python so looking for some tips on what is my best options here to produce such a json file with array structure ? 我是python的新手,因此想在这里找到一些最佳建议,以生成具有数组结构的json文件,这是我最好的选择?
Json file 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 Script 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)
There's a library for that! 有一个图书馆!
import json
Using this you can take your data structure... and convert it to json! 使用此方法,您可以获取数据结构...并将其转换为json!
data = [1, 2, 3, {"hello world":42}]
myjson = json.dumps(data)
...and that's basically it. ...基本上就是这样。 use json.loads
and json.load
to load from a json class and json file respectively. 使用json.loads
和json.load
分别从json类和json文件加载。
You can find out more at this website 您可以在此网站上找到更多信息
PS If you want to print with an indent, try PS如果要打印缩进,请尝试
some_dictionary = {'hostname':hostname, 'PublicIP':publicIp, etc}
print(json.dumps(some_dictionary, indent=4))`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.