pingset.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os, platform, webbrowser, json
  2. import subprocess as sp
  3. import datetime as dt
  4. from jinja2 import Environment, FileSystemLoader
  5. from tqdm import tqdm
  6. env = Environment(
  7. loader=FileSystemLoader('templates')
  8. )
  9. def get_state_ping(ip_address):
  10. if platform.system() in 'Linux':
  11. command = "ping -w 1 -c 1 %s"
  12. else:
  13. command = "ping -n 1 %s"
  14. try:
  15. status, result = sp.getstatusoutput(
  16. command % (ip_address)
  17. )
  18. except ValueError:
  19. return 1
  20. return status
  21. def ip_check(ip: str, count: int) -> dict:
  22. pbar = tqdm()
  23. pbar.reset(total=count)
  24. count_good_ping = 0
  25. time = dt.datetime.now().strftime('%H:%M:%S')
  26. for _ in range(count):
  27. if get_state_ping(ip) == 0:
  28. count_good_ping += 1
  29. pbar.update()
  30. pbar.refresh()
  31. return {
  32. "ip": ip,
  33. "good_ping": count_good_ping,
  34. "time": time
  35. }
  36. def start(params: dict):
  37. list_result = []
  38. for ip in params.get('list_ip'):
  39. print(F"Check ip: {ip}")
  40. list_result.append(ip_check(ip, int(params.get('count'))))
  41. template = env.get_template("template.html")
  42. render_template = template.render({
  43. "count": params.get('count'),
  44. "list_result": list_result,
  45. "date": dt.date.today(),
  46. })
  47. html_path = os.path.join(os.path.dirname(__file__), F"report_{dt.datetime.today().timestamp()}.html")
  48. with open(html_path, 'w') as f:
  49. f.write(render_template)
  50. webbrowser.open(F"file://{html_path}", new=2)
  51. if __name__ == "__main__":
  52. data_from_json = None
  53. if os.path.exists('settings.json'):
  54. with open('settings.json') as f:
  55. data_from_json = json.load(f)
  56. start(data_from_json)