forked from shmuelzon/esp32-ble2mqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote_log.py
66 lines (56 loc) · 1.78 KB
/
remote_log.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
#!/usr/bin/env python
from __future__ import print_function
from builtins import str
import argparse
import datetime
import ipaddress
import json
import os
import socket
import struct
dns_cache = dict()
def get_hostname(addr):
ip = addr[0]
try:
if dns_cache.get(ip) == None:
name, alias, addresslist = socket.gethostbyaddr(ip)
dns_cache[ip] = name
return dns_cache[ip]
except socket.herror:
return ip
def log_listener(args):
ip = ipaddress.ip_address(str(socket.gethostbyname(args.host)))
# Set up logging server
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if ip.is_multicast:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
mreq = struct.pack("4sl", socket.inet_aton(str(ip)), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
sock.bind(('', args.port))
print('Listening on port %d' % args.port)
while True:
try:
data, addr = sock.recvfrom(2048)
print('%s (%s): %s' % (datetime.datetime.now(), get_hostname(addr),
data.decode()), end='')
except KeyboardInterrupt:
break;
def main():
parser = argparse.ArgumentParser(description='Remote logging server')
parser.add_argument('--host', help='Host or IP address to listen on. '
'Default take from configuration file')
parser.add_argument('--port', type=int, help='UDP port to listen on. '
'Default take from configuration file')
args = parser.parse_args()
config = json.load(open('data/config.json'))
try:
if args.host is None:
args.host = config['log']['host']
if args.port is None:
args.port = config['log']['port']
except KeyError:
print('Logging seems to be disabled in the configuration file')
return
log_listener(args)
if __name__ == '__main__':
main()