Python 100 project #40: Syslog Server

I’m using Sophos XG Firewall VM at home. It is fantastic in terms of the feature and UI, it really works well and suits my needs for daily web surfing (and its protection). But it lacks some enterprise features. One of the measure feature I need these kind of device is alert customization. It should be able to notify the admin if any changes(or event) occurs.

At this moment, it is in the vote list, but there is no plan this function to be supported. Hence I decided to use syslog to get customized alert in real time. As a first step, I searched python3 powered syslog server, and modified a bit.


Here is the syslog server output:

# python3.6 testlog.log :  b'<134>device="SFW" date=2018-06-11 time=00:20:46 timezone="BST" device_name="SFVH" device_id=C01001QMP929K6A log_id=050902616002 
log_type="Content Filtering" log_component="HTTP" log_subtype="Denied" status="" priority=Information fw_rule_id=2 user_name="" user_gp="" 
iap=12 category="Gambling" category_type="Objectionable" url="" contenttype="" override_token="" httpresponsecode="" 
src_ip= dst_ip= protocol="TCP" src_port=62469 dst_port=443 sent_bytes=0 recv_bytes=0 exceptions= 
activityname="Not Suitable for Schools" reason="" user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36" 
status_code="403" transactionid= referer=""'


Here is the code:

## Reference

## 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.

# LOG_FILE = 'youlogfile.log'
HOST, PORT = "", 514


import logging
import socketserver
import sys

class SyslogUDPHandler(socketserver.BaseRequestHandler):

    def handle(self):
        data = bytes.decode(self.request[0].strip(), encoding="utf-8")
        socket = self.request[1]
        print("%s : " % self.client_address[0], str(data.encode("utf-8")))"utf-8")))

if __name__ == "__main__":

    if len(sys.argv) != 2:
        print(f"Usage: {sys.argv[0]} log_file_name")

        LOG_FILE = sys.argv[1]
        logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='', filename=LOG_FILE, filemode='a')
        server = socketserver.UDPServer((HOST,PORT), SyslogUDPHandler)
    except (IOError, SystemExit):
    except KeyboardInterrupt:
        print ("Crtl+C Pressed. Shutting down.")