【问题标题】:Ping multiple ips and write to JSON file pythonping 多个 ip 并写入 JSON 文件 python
【发布时间】:2019-02-15 11:11:55
【问题描述】:

我正在 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"}}

【问题讨论】:

  • 我知道这听起来有点奇怪,但是您可以将数据写入 mongodb 数据库而不是将其写入 json,然后将该数据库导出到 json 文件中?
  • 我认为如果您使用 sqlite 而不是 JSON 文件,您的监控解决方案的扩展性会更好。只需创建一个简单的表(字段:时间戳、主机、状态)并将数据插入到该表中。看这里怎么做:sqlitetutorial.net/sqlite-python

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


【解决方案1】:

要继续向现有文件添加内容而不覆盖现有内容,您应该以“追加”模式打开。在您的代码中,您以“写入”模式打开。这将打开文件进行写入,但会覆盖现有内容。

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

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

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

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

如果这能解决您的问题,请告诉我。

【讨论】:

  • 没有。它没有解决我的问题。数据应该在 JSON 中的 { } 内更新,但它正在追加一个新的
  • 那是因为你没有更新它!您正在添加一个新的:` data[timestamp] = { 'monitor.ip':str(hosts), 'monitor.status': u } ` 而应该是: ` data[timestamp]['monitor.ip '] = str(hosts) data[timestamp]['monitor.status'] = 'you value here' `
  • 您还会在 JSON 中获得两个时间戳键,因为它们是不同的时间戳值。
  • JSON 不是框架协议,即您不能附加到有效的 JSON 并获得有效的 JSON。但请看这里:ndjson.org
  • data[timestamp]['monitor.ip'] = str(hosts) data[timestamp]['monitor.status'] = 'you value here' => 不能解决我的问题。任何其他解决方案..
【解决方案2】:

以下是代码的精简版:

import os
from multiprocessing import Pool
import json
import datetime
import time

hosts = ["192.168.1.47", "8.8.8.8"]
MAX_NUMBER_OF_STATUS_CHECKS = 2
FILE_NAME = 'hosts_stats.json'


#
# counter and sleep were added in order to simulate scheduler activity  
#

def ping(host):
    status = os.system('ping  -o -c 3 {}'.format(host))
    return datetime.datetime.now().strftime("%B %d %Y, %H:%M:%S"), {"monitor.ip": host,
                                                                "monitor.status": 'UP' if status == 0 else 'DOWN'}


if __name__ == "__main__":
    p = Pool(processes=len(hosts))
    counter = 0
    if not os.path.exists(FILE_NAME):
        with open(FILE_NAME, 'w') as f:
            f.write('{}')
    while counter < MAX_NUMBER_OF_STATUS_CHECKS:
        result = p.map(ping, hosts)
        with open(FILE_NAME, 'rb+') as f:
            f.seek(-1, os.SEEK_END)
            f.truncate()
            for entry in result:
                _entry = '"{}":{},\n'.format(entry[0], json.dumps(entry[1]))
                f.writelines(_entry)
             f.write('}')
        counter += 1
        time.sleep(2)

【讨论】:

  • 代码将根据计划每分钟运行一次。但是这段代码重写了整个 JSON 文件
  • 保罗·史蒂文。代码已根据您的评论修改
  • 但它不会成为有效的 JSON 文件。
  • 查看我需要的输出
  • 保罗·史蒂文。代码又被修改了。添加了函数 load_hosts_stats() 以便将文件加载到字典列表中。这非常接近我希望的所需输出。
猜你喜欢
  • 2023-01-03
  • 2023-01-25
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多