pingset.py 1.8 KB

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