summaryrefslogtreecommitdiffstats
path: root/ansible_collections/infinidat/infinibox/scripts/syslog_server.py
blob: fe7f6d18da38d7b798a4c32787cbed54ab64b4a0 (plain)
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
#!/usr/bin/env python

"""
Tiny Syslog Server in Python.

This is a tiny syslog server that is able to receive UDP based syslog
entries on a specified port and save them to a file.
That's it... it does nothing else...
There are a few configuration parameters. These can be set via env vars.
Usage: sudo ./syslog_server.py
"""

import os
import logging
import socketserver

# User Configuration variables:
LOG_FILE = os.environ.get('LOG_FILE', 'syslog.log')
HOST = os.environ.get('HOST', "0.0.0.0")
PORT = int(os.environ.get('PORT', 514))

logging.basicConfig(
    level=logging.INFO,
    format='%(message)s',
    datefmt='',
    filename=LOG_FILE,
    filemode='a'
)


class SyslogUDPHandler(socketserver.BaseRequestHandler):
    """ A handler """

    def handle(self):
        """ Handle data """
        data = bytes.decode(self.request[0].strip())
        # socket = self.request[1]
        print(f"{self.client_address[0]}: {str(data)}")
        logging.info(str(data))


if __name__ == "__main__":
    try:
        server = socketserver.UDPServer((HOST, PORT), SyslogUDPHandler)
        print(f"Starting server on host {HOST}:{PORT} using file {LOG_FILE}...")
        server.serve_forever(poll_interval=0.5)
    except PermissionError:
        print("Permission denied while trying to start the server. Try sudo.")
    except (IOError, SystemExit):  # pylint: disable=try-except-raise
        raise
    except KeyboardInterrupt:
        print("\nShutting down...")