-
Notifications
You must be signed in to change notification settings - Fork 1
/
smart4-vdsl
executable file
·168 lines (134 loc) · 5.63 KB
/
smart4-vdsl
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
#!/usr/bin/env python3
import json
import sys
import os
import argparse
import requests
import datetime
from time import sleep
from influxdb import line_protocol
from Crypto.Cipher import AES
FORMAT_JSON = 'json'
FORMAT_INFLUXDB = 'influxdb'
FORMAT_RAW = 'raw'
OUTPUT_FORMATS = [ FORMAT_JSON, FORMAT_INFLUXDB, FORMAT_RAW ]
DEFAULT_HOSTNAME = '169.254.2.1'
DEFAULT_PORT = 80
DEFAULT_KEY = 'cdc0cac1280b516e674f0057e4929bca84447cca8425007e33a88a5cf598a190'
DEFAULT_FORMAT = FORMAT_JSON
STATUS_ROUTE = '/data/Status.json'
HTTP_TIMEOUT = 5
MAX_RETRIES = 3
RETRY_WAIT = 3
MEASUREMENT_NAME = "smart4_vdsl_status"
REPORT_FIELDS = [ 'dsl_link_status', 'dsl_downstream', 'dsl_upstream', 'firmware_version' ]
# Fields are strings by default. Cast these to integers and optionally divide by 1,000:
BPS_FIELD = [ 'dsl_downstream', 'dsl_upstream' ]
def http_get_encrypted_json(encryptionKey, url, params={}):
res = None
error_msg = None
for i in range(MAX_RETRIES+1):
try:
headers = { 'Accept': 'application/json' }
response = requests.get(url, params=params, headers=headers, timeout=HTTP_TIMEOUT)
try:
res = response.json()
except ValueError:
try:
decrypted = decrypt_response(encryptionKey, response.text)
res = json.loads(decrypted)
except ValueError as e:
error_msg = "Decryption or JSON parsing failed: %s" % e
eprint(error_msg)
continue
except Exception as e:
error_msg = "Error: %s" % e
eprint(error_msg)
if i < MAX_RETRIES:
eprint("Will do %i. retry in %i sec(s)..." % (i+1, RETRY_WAIT ))
sleep(RETRY_WAIT)
else:
eprint("Maximum number of retries exceeded, giving up")
continue
break
return res, error_msg
def decrypt_response(keyHex, data):
# thanks to https://stackoverflow.com/a/69054338/1387396
key = bytes.fromhex(keyHex)
nonce = bytes.fromhex(keyHex)[:8]
ciphertextTag = bytes.fromhex(data)
ciphertext = ciphertextTag[:-16]
tag = ciphertextTag[-16:]
cipher = AES.new(key, AES.MODE_CCM, nonce)
decrypted = cipher.decrypt_and_verify(ciphertext, tag)
return decrypted.decode('utf-8')
def get_field(report, name, divide_by_thousand=False):
field = next((x for x in report if x['varid'] == name), None)
if name in BPS_FIELD:
value = int(field['varvalue'])
if divide_by_thousand:
return int(value / 1000)
return value
return field['varvalue']
def get_vdsl_status(hostname, port, key, raw=False, divide_by_thousand=False, return_error=False):
url = "http://%s:%i%s" % ( hostname, port, STATUS_ROUTE )
report, error_msg = http_get_encrypted_json(key, url)
if not report:
eprint("Failed to get status from %s" % url)
if return_error:
if raw:
return ''
else:
return { "error": 1, "error_msg": error_msg }
return None
if raw: return report
status = {}
for field in REPORT_FIELDS:
status[field] = get_field(report, field, divide_by_thousand)
return status
def get_data_points(vdsl_status):
data = { "points": [] }
time = get_current_utc_time()
data["points"].append({
"measurement": MEASUREMENT_NAME,
"fields": vdsl_status,
"time": time
})
return data
def get_formatted_output(status, format):
if (format == FORMAT_INFLUXDB):
return line_protocol.make_lines(get_data_points(status))
elif (format in [ FORMAT_JSON, FORMAT_RAW ]):
return json.dumps(status)
else:
eprint("Unknown format %s" % format)
return ''
def get_current_utc_time():
return datetime.datetime.utcnow().replace(microsecond=0).isoformat()
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--hostname", default=DEFAULT_HOSTNAME,
help="Specify hostname or IP address (defaults to %s)" % DEFAULT_HOSTNAME)
parser.add_argument("--port", default=DEFAULT_PORT, type=int,
help="Specify port (defaults to %i" % DEFAULT_PORT)
parser.add_argument("--key", default=DEFAULT_KEY,
help="Specify key for AES decryption (defaults to %s)" % DEFAULT_KEY)
parser.add_argument("--format", default=DEFAULT_FORMAT,
help="Specify the output format (one of %s; defaults to %s)" % ( ', '.join(OUTPUT_FORMATS), DEFAULT_FORMAT ) )
parser.add_argument("--divide-by-thousand", action='store_true',
help="Divide sync values by 1,000 (newer firmware versions report in bps instead of kbps), doesn't apply when format is set to %s" % FORMAT_RAW)
parser.add_argument("--return-error", action='store_true',
help="Return error message in specified output format (not supported for format %s). If not set, the script will exit with code 1 without printning anything to stdout." % FORMAT_RAW)
params = parser.parse_args()
if (params.return_error and params.format == FORMAT_RAW):
eprint("--format %s and --return-error cannot be combined" % FORMAT_RAW)
exit(1)
status = get_vdsl_status(params.hostname, params.port, params.key,
params.format == FORMAT_RAW, params.divide_by_thousand,
params.return_error)
if not status: exit(1)
print(get_formatted_output(status, params.format))
if __name__ == '__main__':
main()