Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import platform
- import subprocess
- import time
- import datetime
- IP_PARA_LOG = "1.1.1.1"
- print_in_terminal = True
- log_text = False
- def ping(host):
- if platform.system().lower() == "windows":
- ping_cmd = f"ping -n 1 {host}"
- else:
- ping_cmd = f"ping -w 3 -c 1 {host}"
- output = subprocess.getoutput(ping_cmd)
- if "unreachable" in output or "100% packet loss" in output:
- return False
- else:
- return True
- def calcular_uptime(t_init, t_end):
- if (t_init == 0):
- return datetime.timedelta(hours = (t_end.hour - 3), minutes=t_end.minute, seconds=t_end.second)
- elif t_end == 0:
- return datetime.timedelta(hours = (t_init.hour - 3), minutes=t_init.minute, seconds=t_init.second)
- time_init = datetime.timedelta(hours = t_init.hour, minutes=t_init.minute, seconds=t_init.second)
- time_end = datetime.timedelta(hours = t_end.hour, minutes=t_end.minute, seconds=t_end.second)
- return (time_end - time_init)
- def formatar_timedelta(timedelta):
- horas = timedelta.seconds // 3600
- minutos = (timedelta.seconds // 60) % 60
- segundos = timedelta.seconds % 60
- return f"{horas:02d}h {minutos:02d}min {segundos:02d}s"
- def main():
- init_time = datetime.datetime.now()
- init_down = 0
- start_msg = f"Monitoramento ativo desde o dia {datetime.date.today().strftime('%d/%m/%Y')}"
- logname = f"{datetime.date.today()}_{time.time()}_uptime.txt"
- print(f"\x1b[0;34;40m{start_msg}\x1b[0m")
- while True:
- if ping(IP_PARA_LOG):
- con_restart = f"Conexão com a internet foi Restaurada {formatar_timedelta(calcular_uptime(datetime.datetime.now(), 0))}"
- uptime = formatar_timedelta(calcular_uptime(init_time, datetime.datetime.now()))
- logmessage = f"Conexão com a internet está ativa por {uptime}"
- if init_down != 0:
- print(f"\x1b[0;33m{con_restart}\x1b[0m")
- subprocess.getoutput(f"echo '{con_restart}' >> {logname}")
- if print_in_terminal:
- subprocess.getoutput(f"echo '{logmessage}' >> {logname}")
- print(f"\x1b[32;40m{logmessage}\x1b[0m", end="\r", flush=True)
- init_down = 0
- else:
- if init_down == 0:
- print()
- init_down = datetime.datetime.now()
- con_down = f"Conexão com a internet está off-line {formatar_timedelta(calcular_uptime(datetime.datetime.now(), 0))}"
- print(f"\x1b[0;31;40m{con_down}\x1b[0m")
- subprocess.getoutput(f"echo '{con_down}' >> {logname}")
- if print_in_terminal:
- print("", end="\r", flush=True)
- init_time = datetime.datetime.now()
- time.sleep(5)
- main()
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement