-
Notifications
You must be signed in to change notification settings - Fork 0
/
checks.py
101 lines (85 loc) · 2.88 KB
/
checks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import os
from datetime import datetime
import urllib.request, urllib.error
import subprocess
from pprint import pprint
import requests
import hjson
def do_portal(username, password):
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username': username, 'password': password}
session = requests.Session()
portal_url = 'https://portal.4cd.edu:9998/forms/user_login'
res = session.post(portal_url, headers=headers, data=payload)
print(res.text)
def internet_on(url, check_str):
try:
resp = urllib.request.urlopen(url, timeout=1)
text = resp.read()
if check_str.encode() not in text:
return False
return True
except urllib.error.URLError as err:
return False
def get_wpa_status(*, interface=None):
interface_select = ["-i", interface] if interface else []
cmd = ["/sbin/wpa_cli"] + interface_select + ["status"]
output = subprocess.check_output(cmd)
output = output.decode('utf8')
output = output.split("\n")
output = [o.split("=") for o in output if o and '=' in o]
output = {k: v for k, v in output}
#print(output)
return output
def ensure(search_str, call_args):
ps = subprocess.check_output(["ps", "aux"])
ps = ps.decode('utf8')
#print(ps)
running = search_str in ps
started = False
start_failed = False
if not running:
call_args[1:] = (os.path.expanduser(p) for p in call_args[1:])
res = subprocess.call(call_args)
if res == 0:
started = True
else:
start_failed = True
return {
'running': running,
'started': started,
'start_failed': start_failed,
}
def get_config(config_path=None):
if config_path is None:
config_path = os.environ.get('TUNNEL_CONFIG', '~/tunnel/config.hjson')
config_path = os.path.expanduser(config_path) #expand ~
with open(config_path) as f:
config = hjson.loads(f.read())
return config
def main():
print(datetime.now())
config = get_config()
#pprint(config)
iok = internet_on(config['internet']['url'], config['internet']['str'])
print("internet", iok)
interface = config.get('interface', "wlan0")
wpa_status = get_wpa_status(interface=interface)
ssid = wpa_status.get('ssid')
print("ssid", ssid)
print("ip", wpa_status.get('ip_address'))
if ssid in config['portal_ssids'] and not iok:
try:
auth = config['portal_auth']
do_portal(auth['user'], auth['pass'])
except requests.exceptions.ConnectionError as e:
print("portal error:", e)
for proc_name, proc in config.get('ensure', {}).items():
print(proc_name)
result = ensure(proc['ps'], proc['run'])
for sr, status in result.items():
if status:
print(" ", sr)
print()
if __name__ == "__main__":
main()