-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwiretap.py
More file actions
77 lines (63 loc) · 2.11 KB
/
Copy pathwiretap.py
File metadata and controls
77 lines (63 loc) · 2.11 KB
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
import logging
import sys
import requests
import json
import asyncio
import websockets
import signal
from event import Event
def setup_logging():
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
logging.info('Welcome to wiretap')
logging.info('I monitor the websockets at the IPs you provide and write the data to log files')
logging.info('Press Ctrl+C to exit')
def get_websocket_url(addr):
"""
Sends a request to register with the websocket. Returns the websocket url
"""
try:
r = requests.get(f'http://{addr}:3012/register')
except Exception as e:
logging.error(f"The Iris server at {addr} didn't respond. Is it running? Do you have the right IP?")
logging.error(e)
sys.exit(1)
assert r.status_code == 200
url = json.loads(r.text)['url']
logging.info(f"Registered with {addr} and got websocket url: `{url}`")
return url
async def on_message(message):
"""
Incoming websocket messages are sent here
"""
event = Event(message)
if event.should_be_logged():
event.write_to_file()
else:
logging.warning(f"Received an event that we don't want to keep: {event.response_type} with message {event.message}")
async def watch_iris_server(url):
"""
Connects to the websocket and loops indefinitely, saving the output
to a file
"""
async with websockets.connect(url, ping_interval=None) as websocket:
logging.info('Connected to iris server')
while True:
await on_message(await websocket.recv())
def signal_handler(sign, frame):
print()
logging.info("Ctrl+C pressed. Exiting...")
sys.exit(0)
async def main():
setup_logging()
signal.signal(signal.SIGINT, signal_handler)
if len(sys.argv) < 2:
print('Usage: python wiretap.py [RTU ip addresses..]')
sys.exit(1)
urls = [get_websocket_url(ip) for ip in sys.argv[1:]]
tasks = [watch_iris_server(url) for url in urls]
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())