Search code examples
pythonsocketssyslog

Python Syslog server for network devices


Creating a python syslog server for my network devices I am using the below code that comes from here https://gist.githubusercontent.com/marcelom/4218010/raw/53b643bd056d03ffc21abcfe2e1b9f6a7de005f0/pysyslog.py

This will meet my needs but I cannot seem to get any python version of sysloghandler to run. I see this is old code about 5 years or so. I am running ubuntu 16.04 system. Everything seems to hang on the try: for initiating the server.

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

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

#
# NO USER SERVICEABLE PARTS BELOW HERE...
#

import logging
import SocketServer

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

class SyslogUDPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = bytes.decode(self.request[0].strip())
        socket = self.request[1]
        print( "%s : " % self.client_address[0], str(data))
        logging.info(str(data))

if __name__ == "__main__":
    try:
        server = SocketServer.UDPServer((HOST,PORT), SyslogUDPHandler)
        server.serve_forever(poll_interval=0.5)
    except (IOError, SystemExit):
        raise
    except KeyboardInterrupt:
        print ("Crtl+C Pressed. Shutting down.")

Solution

  • Your code works for me. If I start the server like this:

    sudo python server.py
    

    And then send a message like this:

    echo this is a test | nc -u localhost 514
    

    I see output on stdout:

    ('127.0.0.1 : ', 'this is a test')
    

    And the file youlogfile.log contains:

    this is a test
    

    I suspect your problems stem from trying to use a TCP tool to connect to a UDP server.