ping多个ip并写入JSON文件python

时间:2019-02-15 11:11:55

标签: python json python-3.x multiprocessing subprocess

我正在ping局域网中的多个IP,以检查它是否仍在运行。该代码将根据计划每分钟运行一次。对于ping多个IP,我使用了多重处理。借助多处理,可以很好地完成此工作。同时,我想在ping后将ping结果写入json文件。但是当写入JSON文件时,它仅写入最后一个ip的输出。我想要所有这三个。 有没有办法做到这一点

这是示例代码:

import json
from multiprocessing import Pool
import subprocess
from datetime import datetime
timestamp = datetime.now().strftime("%B %d %Y, %H:%M:%S")
hosts =  ["192.168.1.47","192.168.1.42"]
count = 1
wait_sec = 1
n = len(hosts)
def main(hosts):
    p = Pool(processes= n)
    result = p.map(beat, hosts)
def beat(hosts):
    #Name for the log file
    name = 'icmp.json'
    ip4write(hosts, name)
def ip4write(hosts, name):
    global ip4a
    ip4a = hosts
    ipve4(hosts, name)
    write(hosts, name)
def ipve4(hosts, name):
    global u
    status, result = subprocess.getstatusoutput("ping -c1 -w2 " + str(ip4a))
    if status == 0:
        print(str(ip4a) + " UP")
        u = " UP"
def write(hosts, name):
    text_file = open(name, "a+")
    with open(name) as json_file:
      try:
          data = json.load(json_file)
      except:
          data = {}
      with open(name, 'w') as outfile:
        data[timestamp] = {
          'monitor.ip':str(hosts),
          'monitor.status': u
        }
        print(data)
        json.dump(data, outfile)
        print('Data written')
    text_file.close()
main(hosts)

JSON文件中的输出:

{"February 15 2019, 16:38:12": {"monitor.status": " UP", "monitor.ip": "192.168.1.42"}}

我所需的输出:

{"February 15 2019, 16:38:12": {"monitor.ip": "192.168.1.47", "monitor.status": " UP"}, "February 15 2019, 16:38:12": {"monitor.ip": "192.168.1.42", "monitor.status": " UP"}}

2 个答案:

答案 0 :(得分:0)

要在不覆盖现有内容的情况下继续向现有文件添加内容,则应在“附加”模式下打开。在您的代码中,您以“写入”模式打开。它将打开文件进行写入,但将覆盖现有内容。

具体来说,您代码中的这一行:

with open(name, 'w') as outfile:

您应该将打开模式从写入('w')更改为追加('a')。

with open(name, 'a') as outfile:

让我知道这是否可以解决您的问题。

答案 1 :(得分:0)

下面是代码的紧凑版本:

import requests

with open('file.xsd', 'r') as f:
    data = f.read()
r = requests.post('https://www.liquid-technologies.com/api/Converter', json={"Filename": "schema.xsd", "Type": "xsd", "Data": data, "TargetType": "xml", "Arguments": {"elementName": "Root", "elementNamespace": "", "addAnyAttributes": False, "addAnyElements": False, "forceOptionItemsToDepthOf": "4", "forceXsiNamespaceDelaration": False, "maxDepthToCreateOptionalItems": "7", "indent": "2", "indentChar": " ", "indentAttributes": False, "seed": "9722"}})
with open('file.xml', 'w') as f:
    f.write(r.json()['Files'][0]['Data'])