Jun-27-2022, 08:28 AM
(Jun-27-2022, 08:02 AM)AlphaInc Wrote:(Jun-27-2022, 07:16 AM)ibreeden Wrote: No. You must read the ip addresses from the json file one by one, and for each address test if it responds.
from subprocess import call, DEVNULL import platform import json import os def folder(): path = os.getcwd() newPath = path + "/tmp" os.mkdir(newPath) def ping(host_or_ip: str) -> bool : """ping(): execute one ping to host_or_ip. Returns True if host_or_ip responded, else False. """ if platform.system().lower() == "windows": countoption = "/n" else: countoption = "-c" return not call(["ping", countoption, "1", host_or_ip], stdout=DEVNULL, stderr=DEVNULL) responding_hosts = 0 with open("clients.json") as f: data = json.load(f) for i in data: print(f"pinging: {i['ip']}") if ping(i["ip"]): responding_hosts += 1 print(f"Number of responding hosts: {responding_hosts}") if responding_hosts > 0 : folder()
Okay nice, this worked great!
Sorry, but I have one last question. I tried to check for two different json files (one contains a list of IPs which should be offline and one which should be online) but I'm running into some problems once again:
#!/usr/bin/env python3 #Imports from subprocess import call, DEVNULL import platform import json import os #IP Configuration responding_clients1 = 0 responding_clients2 = 0 #Folder Creation def folder(): path = os.getcwd() newPath = path + "/tmp" os.mkdir(newPath) #Pinp Configuration def ping(host_or_ip: str) -> bool : if platform.system().lower() == "windows": countoption = "/n" else: countoption = "-c" return not call(["ping", countoption, "1", host_or_ip], stdout=DEVNULL, stderr=DEVNULL) #Clients1 Check with open("clients1.json") as f1: data1 = json.load(f1) for i in data1: if ping(i["ip"]): responding_clients1 += 1 #Clients2 Check with open("clients2.json") as f2: data2 = json.load(f2) for i in data2: if ping(i["ip"]): responding_clients2 += 1 #ToDo if responding_clients1 > 0 : if responding_clients2 == 0: folder() #End sys.exit()And I get this error message:
Traceback (most recent call last): File "/home/pi/system/debug/ipCheck/v1.0.py", line 37, in <module> data2 = json.load(f2) File "/usr/local/lib/python3.10/json/__init__.py", line 293, in load return loads(fp.read(), File "/usr/local/lib/python3.10/json/__init__.py", line 346, in loads return _default_decoder.decode(s) File "/usr/local/lib/python3.10/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/lib/python3.10/json/decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 9 column 3 (char 112)
Nevermind, there was a missing comma in my second .json file. Thank you all for your help