-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup_wifi.py
executable file
·208 lines (189 loc) · 8.93 KB
/
setup_wifi.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
# Script for changing MultiAP WiFi settings in Teltonika RUTX11.
# Requires RUTX11 device with configuration set by factory_settings.sh script - by default done by Husarion during production.
from click import secho
import io
import json
import os
from pssh.clients import SSHClient
import pssh.exceptions
import subprocess
import sys
import time
allowed_radio = ['0', '1']
host = '10.15.20.1' # IP adress of RUTX11
user_name = 'root'
config_file = 'config.json'
reconfigure_wifi = False
reconfigure_client = False
debug_flag = False # if true print debug messages
try:
ssh = SSHClient(host, user=user_name, timeout=5, num_retries=1)
except pssh.exceptions.AuthenticationError as e:
secho("SSH connection failed. Most likely there is no / not valid SSH public key on router. https://husarion.com/manuals/panther/troubleshooting/#rutx11-issues", fg='red', bold=True)
sys.exit("Exiting.")
except pssh.exceptions.SessionError as e:
secho("SSH connection failed.", fg='red', bold=True)
sys.exit("Exiting.")
except pssh.exceptions.SSHError as e:
secho("SSH connection failed.", fg='red', bold=True)
sys.exit("Exiting.")
except pssh.exceptions.ConnectionError as e:
secho("SSH connection failed. Most likely router is not available or on difrent IP. https://husarion.com/manuals/panther/troubleshooting/#rutx11-issues", fg='red', bold=True)
sys.exit("Exiting.")
def multi_wifi_config_validator(data, name):
for index, key in enumerate(data, start=1):
try:
if key['ssid'] == '':
raise KeyError
except KeyError:
secho("No SSID for {} entry {}".format(name, index), fg='red', bold=True)
sys.exit("Exiting.")
try:
key['password']
if len(key['password']) < 8:
if key['password'] == '':
secho("No password for {} entry {}. Assuming open network. Make sure it is correct.".format(name, index))
key['password'] = None
else:
raise ValueError("Password for {} entry {} is shorter than minimal lenght of 8".format(name, index))
except ValueError as e:
secho(e, fg='red', bold=True)
sys.exit("Exiting.")
except KeyError:
secho("No password for {} entry {}. Assuming open network. Make sure it is correct.".format(name, index), fg='yellow', bold=True)
key['password'] = None
def set_multi_wifi(ssid, password, priority):
command = "uci add multi_wifi wifi-iface\n"
command += "uci set multi_wifi.@wifi-iface[-1].ssid='{}'\n".format(ssid)
if password != None:
command += "uci set multi_wifi.@wifi-iface[-1].key='{}'\n".format(password)
command += "uci set multi_wifi.@wifi-iface[-1].enabled='1'\n"
command += "uci set multi_wifi.@wifi-iface[-1].priority='{}'\n".format(priority)
return command
# Verify RUTX firmware version. Versions RUTX_R_00.07.02.07 and higher are supported.
try:
output = ssh.run_command("cat /etc/version")
firmware_version_raw = None
for line in output.stdout:
firmware_version_raw = line
if firmware_version_raw == None:
secho("Could not verify RUTX11 firmware version. Exiting.", fg='red', bold=True)
sys.exit()
firmware_version = str.split(firmware_version_raw,'.')
if firmware_version[0] != "RUTX_R_00":
secho("Could not verify RUTX11 firmware version. Obtained version string {}. Exiting.".format(firmware_version_raw), fg='red', bold=True)
sys.exit()
elif int(firmware_version[1]) < 7 or (int(firmware_version[1]) == 7 and int(firmware_version[2]) < 2):
secho("Detected RUTX11 firmware version {} is not supported by this script.\nCheck https://husarion.com/manuals/panther/rutx11-support/ for help.\nExiting.".format(firmware_version_raw), fg='red', bold=True)
sys.exit()
elif int(firmware_version[1]) == 7 and int(firmware_version[2]) < 4:
secho("Detected RUTX11 firmware version {} is supported by this script.\nConsider updating RUTX11 firmware for stability and performance improvemets.\nCheck https://husarion.com/manuals/panther/rutx11-support/ for help.".format(firmware_version_raw), fg='yellow', bold=True)
else:
secho("Detected RUTX11 firmware version {} is supported by this script.".format(firmware_version_raw), fg='green', bold=True)
except pssh.exceptions.SessionError as e:
secho("SSH connection failed.", fg='red', bold=True)
sys.exit("Exiting.")
# Loading configuration file
try:
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), config_file)
config = open(path,'r')
config = json.load(config)
except json.JSONDecodeError as e:
secho("Could not parse configuration file.", fg='red', bold=True)
secho("{}".format(e), fg='red')
sys.exit("Exiting.")
except:
secho("Could not load configuration file.", fg='red', bold=True)
sys.exit("Exiting.")
# Verify if wifi_client config is present and valid
cmd = ""
try:
config['wifi_client']
except KeyError:
secho("wifi_client section not defined, skipping client configuration")
else:
multi_wifi_config_validator(config['wifi_client'], 'wifi_client')
for priority, key in enumerate(config['wifi_client'], start=1):
cmd += set_multi_wifi(key['ssid'], key['password'], priority)
if debug_flag == True:
secho(cmd)
try:
wifi_client_radio = config['wifi_client_radio']
if wifi_client_radio not in [0,1,'0','1']:
raise TypeError("Allowed values for wifi_client_radio is 0 or 1.")
sys.exit("Exiting.")
except KeyError:
secho("wifi_client_radio not defined, assuming 2.4GHz radio", fg='yellow')
wifi_client_radio = 0
reconfigure_multi_wifi = True
if reconfigure_multi_wifi:
try:
# Get current radio for multi_wifi
output = ssh.run_command("uci get wireless.multi_wifi.device")
used_radio = None
for line in output.stdout:
used_radio = line
if debug_flag == True:
secho(used_radio)
if used_radio != 'radio' + str(wifi_client_radio):
cmd += "uci set wireless.multi_wifi.device='radio" + str(wifi_client_radio) + "';"
if debug_flag == True:
secho("Changing radio")
# Delete multi_wifi WLANs list, write new one
output = ssh.run_command("for x in $(seq $(expr $(uci get multi_wifi.@wifi-iface[-1].priority) - 1) -1 0); do uci delete multi_wifi.@wifi-iface[$x]; done; " + cmd + "uci commit;" + "reload_config")
time.sleep(3)
except pssh.exceptions.ConnectionError:
secho("SSH connection failed, configuration not applied", fg='red', bold=True)
sys.exit("Exiting.")
else:
secho("Router configuration saved")
# Wait till uplink is established - checking via ping to 8.8.8.8 is successful
# Wait 10 seconds to allow router reconfiguration
secho("Pinging 8.8.8.8 to check for internet connection. It can take up to 8 minutes (depending on choosen radio).", fg='yellow', bold=True)
time.sleep(10)
try_count = 1
auth_fail_time = None
kernel_time = None
while subprocess.call(['ping','8.8.8.8','-c','1','-W','1'], stdout=subprocess.DEVNULL):
time.sleep(10)
secho("Waiting to establish an internet connection. Try {}/50".format(try_count))
try_count += 1
if try_count > 50:
secho("Failed to obtain internet connection. \nCheck if choosen WiFi is in range and/or SSID is correct.", fg='red', bold=True)
sys.exit("Exiting")
try:
output = ssh.run_command("cat /proc/uptime | awk '{print $1}'")
kernel_time = None
for line in output.stdout:
kernel_time = line
output = ssh.run_command("dmesg | grep 'denied authentication (status 1)' | tail -1 | awk '{print $2}'")
for line in output.stdout:
auth_fail_time = line
if debug_flag == True:
secho(kernel_time)
secho(auth_fail_time)
except pssh.exceptions.ConnectionError:
secho("SSH connection failed, configuration not applied", fg='red', bold=True)
sys.exit("Exiting.")
if auth_fail_time != None:
auth_fail_time = auth_fail_time[:-1]
else:
continue
if float(auth_fail_time) > float(kernel_time) - 15:
secho("Failed to obtain internet connection.\nPassword is incorrect.", fg='red', bold=True)
sys.exit()
secho("Success. Panther has internet connection.", fg='green', bold=True)
# Connect to husarnet
try:
config['husarnet']
except KeyError:
secho("Husarnet section not defined, skipping Husarnet configuration")
else:
try:
if config['husarnet']['join_code'] == "your_join_code":
secho("Your Husarnet joincode is incorrect, skipping Husarnet configuration")
else:
subprocess.run(["sudo husarnet join " + config['husarnet']['join_code'] + " " + config['husarnet']['hostname']], shell=True)
except KeyError:
secho("Hostname or joincode not defined in husarnet configuration")