Ping多个ips并写入JSON文件python
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ping多个ips并写入JSON文件python相关的知识,希望对你有一定的参考价值。
我在局域网中ping多个ips以检查它是否存活。代码将根据时间表每分钟运行。为了ping多个ips,我使用了多处理。在多处理的帮助下,它做得很好。同时,我想在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"}}
答案
下面是代码的紧凑版本:
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)
另一答案
要在不覆盖现有内容的情况下继续向现有文件添加内容,您应该在“追加”模式下打开。在您的代码中,您将以“写入”模式打开。这将打开文件进行写入,但会覆盖现有内容。
具体来说,代码中的这一行:
with open(name, 'w') as outfile:
您应该将开放模式从write('w'
)更改为append('a'
)。
with open(name, 'a') as outfile:
如果这可以解决您的问题,请告诉我。
以上是关于Ping多个ips并写入JSON文件python的主要内容,如果未能解决你的问题,请参考以下文章
读取带有网络和子网掩码的 csv 并写入带有 ping 结果的文件
让linux系统每隔1分钟ping一个目标IP,目标IP也是linux,获取IP后写入某个文件
需要一个批处理:一直ping一个ip地址,并且把ping的记过写入文本日志文件。且记录下每个ping不通的时间