import os from time import sleep from datetime import datetime from subprocess import Popen, DEVNULL from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class Router: def __init__(self, ip, password): self.ip = ip self.password = password def _ping(self, ip, count=3, timeout=3): process = Popen(['ping', '-c', str(count), '-w', str(timeout), ip], stdout=DEVNULL, stderr=DEVNULL) exit_code = process.wait() return exit_code == 0 def check_lan_connectivity(self): return self._ping(self.ip) def check_internet_connectivity(self): return self._ping('8.8.8.8') def reboot(self): options = webdriver.FirefoxOptions() options.headless = True with webdriver.Firefox(options=options) as driver: driver.get(f'http://{self.ip}/webpages/login.html') sleep(10) password_input = driver.find_elements(By.CSS_SELECTOR, 'input.l[type=password]')[2] password_input.send_keys(self.password) sleep(1) password_input.send_keys(Keys.ENTER) sleep(10) driver.find_element(By.CSS_SELECTOR, 'a#top-control-reboot').click() sleep(1) driver.find_element(By.CSS_SELECTOR, '#reboot_confirm_msg button.btn-msg-ok').click() sleep(1) if __name__ == '__main__': router = Router(os.environ['ROUTER_IP'], os.environ['ROUTER_PASSWORD']) consecutive_internet_downtime = 0 while True: sleep(60) if not router.check_internet_connectivity(): # Internet is down if router.check_lan_connectivity(): # LAN is up if consecutive_internet_downtime >= 2: with open('/logs/connectivity.log', 'a') as log: log.write(f'{datetime.now()} - Internet down, rebooting router\n') consecutive_internet_downtime = 0 router.reboot() sleep(120) else: consecutive_internet_downtime += 1 with open('/logs/connectivity.log', 'a') as log: log.write(f'{datetime.now()} - Internet down\n') else: # LAN is down with open('/logs/connectivity.log', 'a') as log: log.write(f'{datetime.now()} - Internet and LAN down\n') consecutive_internet_downtime = 0 else: consecutive_internet_downtime = 0