3

我有一个子进程正在执行:

lshw -json -C network

如果我收到以下回复:

    {
    "id" : "network",
    "class" : "network",
    "claimed" : true,
    "handle" : "PCI:0000:00:05.0",
    "description" : "Ethernet interface",
    "product" : "82545EM Gigabit Ethernet Controller (Copper)",
    "vendor" : "Intel Corporation",
    "physid" : "5",
    "businfo" : "pci@0000:00:05.0",
    "logicalname" : "eth0",
    "version" : "00",
    "serial" : "00:8c:42:77:58:49",
    "units" : "bit/s",
    "size" : 1000000000,
    "capacity" : 1000000000,
    "width" : 32,
    "clock" : 66000000,
    "configuration" : {
      "autonegotiation" : "on",
      "broadcast" : "yes",
      "driver" : "e1000",
      "driverversion" : "7.3.21-k8-NAPI",
      "duplex" : "full",
      "firmware" : "N/A",
      "ip" : "10.211.55.10",
      "latency" : "0",
      "link" : "yes",
      "multicast" : "yes",
      "port" : "twisted pair",
      "speed" : "1Gbit/s"
    },
    "capabilities" : {
      "msi" : "Message Signalled Interrupts",
      "bus_master" : "bus mastering",
      "cap_list" : "PCI capabilities listing",
      "ethernet" : true,
      "physical" : "Physical interface",
      "logical" : "Logical interface",
      "tp" : "twisted pair",
      "10bt" : "10Mbit/s",
      "10bt-fd" : "10Mbit/s (full duplex)",
      "100bt" : "100Mbit/s",
      "100bt-fd" : "100Mbit/s (full duplex)",
      "1000bt-fd" : "1Gbit/s (full duplex)",
      "autonegotiation" : "Auto-negotiation"
    }
  },

我是否可以对此进行迭代以确保我捕获所有网络接口(如果有多个网络接口),而我的系统并非如此。另外,我如何从这个输出中选择 1 或 2 个,我不需要全部数据。

我想到了以下几点:

 def get_nic_data():
        lshw_cmd = "lshw -json -C network"
        proc = subprocess.Popen(lshw_cmd, shell=True, stdout=subprocess.PIPE,
                                                      stdin=subprocess.PIPE)
        return proc.stdout


 def read_data(proc_output):
        import simplejason as json
        json_obj = json

        json_obj.loads(proc_output)

        #Obtain Vendor,Description,Product
        #...
        #...

        json_obj.dumps(obtained_data_here)

        #Not sure if this would work this way.


  read_data(get_nic_data())
4

2 回答 2

8

不幸的是,您不能将-C类过滤与-json输出结合起来。即使在最新版本中,JSON 输出也严重损坏。相反,请自行过滤完整的JSON 输出。请注意,使用时应避免使用shell=Truesubprocess而是传入一个列表;也不需要管道标准输入,但要捕获(静音)标准错误。

然后我们可以递归“子”结构,挑选出任何具有匹配'class'键的东西:

def get_nic_data():
    lshw_cmd = ['lshw', '-json']
    proc = subprocess.Popen(lshw_cmd, stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
    return proc.communicate()[0]

def find_class(data, class_):
    for entry in data.get('children', []):
        if entry.get('class') == class_:
            yield entry

        for child in find_class(entry, class_):
            yield child

def read_data(proc_output, class_='network'):
    import json

    for entry in find_class(json.loads(proc_output), class_):
        yield entry['vendor'], entry['description'], entry['product']

然后循环read_data(get_nic_data())

for vendor, description, product in read_data(get_nic_data()):
    print vendor, description, product
于 2012-12-17T09:51:31.900 回答
0

如果有多个网卡lshw不返回有效的 json 文本。可以通过在输出之前/之后添加[/并在对象之间添加来修复它:],

import json
import re
from subprocess import STDOUT, check_output as qx

# get command output
output = qx("lshw -json -C network".split(), stderr=STDOUT)

# get json parts
_, sep, json_parts = output.rpartition(b"\r")
if not sep: # no \r in the output
    json_parts = output

# convert it to valid json list
jbytes = b"[" + re.sub(b"}( *){", b"}, {", json_parts) + b"]"
L = json.loads(jbytes.decode())

# pretty print
import sys
json.dump(L, sys.stdout, indent=4)

一个更清洁的解决方案将使用lshw -xml产生的输出,通过将其包装在根元素中,可以轻松地将其转换为格式良好的 xml:'<root>'+ output + '</root>'

于 2012-12-17T10:18:55.363 回答