diff --git a/install b/install new file mode 100755 index 0000000..791a711 --- /dev/null +++ b/install @@ -0,0 +1,31 @@ +#! /usr/bin/env python3 + +import os +from string import Template +from subprocess import check_call + +EXEC = 'wifi-keepalive.py' +SERVICE = 'wifi-keepalive.service' +SYSTEM_DIR = '/etc/systemd/system' + +CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) +EXEC_PATH = os.path.join(CURRENT_DIR, EXEC) +SERVICE_TEMPLATE = os.path.join(CURRENT_DIR, SERVICE) +SERVICE_FILE = os.path.join(SYSTEM_DIR, SERVICE) +EXEC_START = f'python3 {EXEC}' + +with open(SERVICE_TEMPLATE) as f: + serviceTemplate = Template(f.read()) + +serviceFile = serviceTemplate.substitute( + workingDirectory=CURRENT_DIR, + execStart=EXEC_START +) + +with open(SERVICE_FILE, 'w') as f: + f.write(serviceFile) + +check_call(['systemctl', 'daemon-reload']) +check_call(['systemctl', 'enable', '--no-pager', SERVICE]) +check_call(['systemctl', 'restart', '--no-pager', SERVICE]) +check_call(['systemctl', 'status', '--no-pager', SERVICE]) diff --git a/wifi-keepalive.py b/wifi-keepalive.py new file mode 100644 index 0000000..92f318c --- /dev/null +++ b/wifi-keepalive.py @@ -0,0 +1,32 @@ +from signal import SIGTERM, signal +from subprocess import CalledProcessError, check_output +from sys import exit +from time import sleep + +PING_INTERVAL_IN_SECONDS = 80 + +signal(SIGTERM, lambda signum, frame: exit(0)) + + +def getDefaultRoute(): + routes = check_output(['route', '-n']).decode('utf-8').splitlines() + defaults = [r.split()[1] for r in routes if r.startswith('0.0.0.0')] + + return defaults[0] if defaults else None + + +def keepalive(defaultRoute): + while True: + sleep(PING_INTERVAL_IN_SECONDS) + ping(defaultRoute) + + +def ping(address): + try: + check_output(['ping', '-c', '1', address]) + except CalledProcessError as e: + pass + + +defaultRoute = getDefaultRoute() +keepalive(defaultRoute) if defaultRoute else print('No default route') diff --git a/wifi-keepalive.service b/wifi-keepalive.service new file mode 100644 index 0000000..d0e66ad --- /dev/null +++ b/wifi-keepalive.service @@ -0,0 +1,13 @@ +[Unit] +Description=Wifi Keepalive Service +After=multi.user.target + +[Service] +Type=simple +WorkingDirectory=$workingDirectory +ExecStart=$execStart +Restart=on-failure +SyslogIdentifier=wifi-keepalive + +[Install] +WantedBy=multi-user.target