-
Notifications
You must be signed in to change notification settings - Fork 988
/
Copy pathstats_scrapper.py
executable file
·89 lines (71 loc) · 2.64 KB
/
stats_scrapper.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
#!/usr/bin/env python
"""
Retuns the content of a particular table from Admin 'stats' schema.
- Optional params (with default values): '{ "admin_host": "127.0.0.1", "admin_port": 6032, "admin_user": "radmin", "admin_pass": "radmin" }'
- Mandatory params: '{ "table": "tablename" }'
"""
import json
import jsonschema
import sys
import pymysql.cursors
schema = {
"type": "object",
"properties": {
"admin_host": {"type": "string"},
"admin_port": {"type": "number"},
"admin_user": {"type": "string"},
"admin_pass": {"type": "string"},
"table": {"type": "string"},
},
"required": ["table"]
}
def validate_params():
"""Validates the JSON encoded received parameters."""
res = {}
if len(sys.argv) != 2:
res = {"err_code": 1, "res": "Invalid number of parameters"}
else:
try:
j_arg = json.loads(sys.argv[1])
jsonschema.validate(instance=j_arg, schema=schema)
res = {"err_code": 0, "res": ""}
except jsonschema.exceptions.ValidationError as err:
res = {"err_code": 1, "res": "Params validation failed: `" + str(err) + "`"}
except json.decoder.JSONDecodeError as err:
res = {"err_code": 1, "res": "Invalid supplied JSON: `" + str(err) + "`"}
return res
if __name__ == "__main__":
p_res = validate_params()
if p_res["err_code"] != 0:
print(json.dumps(p_res))
exit(0)
params = json.loads(sys.argv[1])
if params.get('admin_host') is None:
params['admin_host'] = "127.0.0.1"
if params.get('admin_port') is None:
params['admin_port'] = 6032
if params.get('admin_user') is None:
params['admin_user'] = "radmin"
if params.get('admin_pass') is None:
params['admin_pass'] = "radmin"
try:
proxy_admin_conn = pymysql.connect(
host=params['admin_host'],
user=params['admin_user'],
password=params['admin_pass'],
port=int(params['admin_port']),
cursorclass=pymysql.cursors.DictCursor,
defer_connect=True
)
proxy_admin_conn.client_flag |= pymysql.constants.CLIENT.MULTI_STATEMENTS
proxy_admin_conn.connect()
proxy_admin_conn.autocommit(True)
except Exception as err:
print(json.dumps({"err_code": 1, "res": "Connection attempt failed: `" + str(err) + "`"}))
exit(0)
s_query = "SELECT * FROM stats.%s"
with proxy_admin_conn:
with proxy_admin_conn.cursor() as cursor:
cursor.execute(s_query, params['table'])
rows = cursor.fetchall()
print(json.dumps({"err_code": 0, "res": rows}))