diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..3b116a4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +FROM python:3.11 + +WORKDIR /code + +ENTRYPOINT ["python", "rebooter.py"] + +RUN apt update --fix-missing +RUN apt install -y firefox-esr iputils-ping + +RUN pip3 install --upgrade pip +COPY requirements.txt . +RUN pip install -r requirements.txt + +COPY src . diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d2389ee --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +selenium==4.9.1 diff --git a/src/rebooter.py b/src/rebooter.py new file mode 100644 index 0000000..f22b3f0 --- /dev/null +++ b/src/rebooter.py @@ -0,0 +1,64 @@ +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(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']) + + while True: + if not router.check_internet_connectivity(): + # Internet is down + if router.check_lan_connectivity(): + # LAN is up + with open('/logs/connectivity.log', 'a') as log: + log.write(f'{datetime.now()} - Internet down') + + router.reboot() + else: + # LAN is down + with open('/logs/connectivity.log', 'a') as log: + log.write(f'{datetime.now()} - Internet and LAN down') + + sleep(60)