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
|
#!/usr/bin/env python3
import logging, json, socket
from aiohttp import web
from argparse import ArgumentParser
routes = web.RouteTableDef()
mss_host = None
mss_port = None
mss_json_response = False
class MySimpleSocketClient:
def __init__(self, port, host):
self._host = host
self._port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self._host, self._port))
def __del__(self):
self.sock.close()
def write(self, line):
self.sock.sendall((line+'\r\n').encode())
def read(self):
buf = bytearray()
while True:
buf.extend(self.sock.recv(256))
if b'\r\n' in buf:
break
response = buf.decode().strip()
return response
@routes.get('/{command}/')
async def variable_handler(request):
command = request.match_info['command']
client = MySimpleSocketClient(host=mss_host, port=mss_port)
client.write(command)
try:
raw = client.read()
if mss_json_response:
response = json.loads(raw)
else:
response = {'data': raw}
except Exception as e:
response = {'error': str(e)}
return web.json_response(response, dumps=lambda x: json.dumps(x, separators=(',', ':')))
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--mss-host', required=True, type=str)
parser.add_argument('--mss-port', required=True, type=int)
parser.add_argument('--mss-json-response', action='store_true')
parser.add_argument('--host', default='0.0.0.0', type=str)
parser.add_argument('--port', default=8080, type=int)
args = parser.parse_args()
mss_host = args.mss_host
mss_port = args.mss_port
mss_json_response = args.mss_json_response
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
app = web.Application()
app.add_routes(routes)
web.run_app(app, host=args.host, port=args.port)
|