· 6 years ago · Oct 22, 2019, 02:02 AM
1import subprocess as sp
2import datetime as dt
3from random import shuffle
4import time
5
6
7interface = 'wlp3s0'
8essid = 'DVFU-HOTEL'
9servers = ['8.8.4.4', 'google.com' 'yandex.ru', 'github.com', 'youtube.com', 'twitch.tv']
10ping = ['ping', '-c', '1']
11interface_down = ['ip', 'link', 'set', interface, 'down']
12interface_up = ['ip', 'link', 'set', interface, 'up']
13connect = ['iwconfig', interface, 'essid', essid]
14dhcp = ['dhcpcd', interface]
15
16
17def proc_output(*args, timeout=None):
18 if timeout:
19 result = sp.run([*args], stdout=sp.PIPE, stderr=sp.STDOUT, timeout=timeout)
20 else:
21 result = sp.run([*args], stdout=sp.PIPE, stderr=sp.STDOUT)
22 result = result.stdout.decode('utf-8')
23 if len(result):
24 return result
25 return None
26
27
28def indentation_print(what: str):
29 for s in what.splitlines():
30 print('\t', s, sep='')
31
32
33def connection():
34 shuffle(servers)
35 timeout_counter = 0
36 for server in servers:
37 try:
38 if '1 packets transmitted, 1 received' in proc_output(*ping, server, timeout=4):
39 return True
40 except sp.TimeoutExpired:
41 timeout_counter += 1
42 if timeout_counter == 3:
43 return False
44 return False
45
46
47while True:
48 if connection():
49 time.sleep(5)
50 continue
51 print('\n', dt.datetime.now().strftime('%H:%M:%S'), ' ', 'Connection lost', sep='')
52 print('Interface down')
53 result = proc_output(*interface_down)
54 if result:
55 indentation_print(result)
56 time.sleep(1)
57 print('Interface up')
58 result = proc_output(*interface_up)
59 if result:
60 indentation_print(result)
61 time.sleep(3)
62 print('Trying to connect')
63 result = proc_output(*connect)
64 if result:
65 indentation_print(result)
66 time.sleep(3)
67 print('Trying to get IP address')
68 result = proc_output(*dhcp)
69 if result:
70 indentation_print(result)
71 time.sleep(10)
72 if connection():
73 print('Connection restored')