adsl-bouncer/adsl.py

116 lines
3.2 KiB
Python

import os
import time
import sys
import subprocess
import re
import config
import lcd
def _get_process_list():
pids = [int(pid) for pid in os.listdir('/proc') if pid.isdigit()]
processes = []
for pid in pids:
try:
with open("/proc/%i/cmdline" % pid, "r") as f:
processes.append(f.read())
except:
pass
return zip(pids, processes)
def _start_pppd():
print " ".join(config.PPPD)
p = subprocess.Popen(config.PPPD, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
sys.stderr.write("Could not run pppd succesfully! Here is some debug data:\n")
sys.stderr.write(" STDOUT: %s\n" % stdout)
sys.stderr.write(" STDERR: %s\n" % stderr)
else:
sys.stdout.write("PPPd started succesfully.\n")
def _get_pppd_pid():
for pid, process in _get_process_list():
if process.startswith("/usr/sbin/pppd"):
return pid
def _kill_pppd():
pid = _get_pppd_pid()
if pid:
os.kill(pid, 9)
sys.stdout.write("Killed PPPd.\n")
def _check_connectivity():
p = subprocess.Popen(config.PING, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
if p.returncode != 0:
sys.stderr.write("There seem to be some connectivity problems... Waiting 15 seconds, then giving it another shot...\n")
time.sleep(15)
p = subprocess.Popen(config.PING, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
if p.returncode != 0:
sys.stderr.write("Connectivity problems persisting! :(\n")
return False
else:
sys.stderr.write("Seems to be okay now.\n")
return True
def _get_public_ip():
p = subprocess.Popen(["ip", "a", "list", "dev", "ppp0"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stderr, stdout = p.communicate()
if p.returncode != 0:
return "UNKNOWN"
else:
for line in stderr.split("\n"):
m = re.match("^inet ([\.0-9]*) peer", line.strip())
if m:
return m.group(1)
return "UNKNOWN"
def loop():
screen = lcd.LCDScreen()
def log(text, text2=None, clear=True):
if clear:
screen.clear()
text = text[:16]
text = ' ' * ((16 - len(text))/2) + text
screen.text_at(0, 0, text)
if text2:
text2 = text2[:16]
text2 = ' ' * ((16 - len(text2))/2) + text2
screen.text_at(0, 1, text2)
while True:
pppd_pid = _get_pppd_pid()
if not pppd_pid:
log("Starting PPPd...")
_start_pppd()
screen.clear()
timeout = 30
while timeout >= 0:
log("PPPd started.", "Testing in %i s. " % timeout, False)
time.sleep(1)
timeout -= 1
log("PPPd started.", "Testing...")
if not _check_connectivity():
sys.stderr.write("Restarting PPPd.\n")
log("ADSL down!", "Restarting PPPd...")
_kill_pppd()
_start_pppd()
log("ADSL down!", "PPPd restarted!")
else:
log("ADSL up!", _get_public_ip())
time.sleep(60)