用于网络设备的 Python Syslog 服务器

标签 python sockets syslog

为我的网络设备创建一个 python syslog 服务器我正在使用来自此处的以下代码 https://gist.githubusercontent.com/marcelom/4218010/raw/53b643bd056d03ffc21abcfe2e1b9f6a7de005f0/pysyslog.py

这将满足我的需求,但我似乎无法运行任何 python 版本的 sysloghandler。我看到这是大约 5 年左右的旧代码。 我运行的是ubuntu 16.04系统。一切似乎都取决于 try: 启动服务器。

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

最佳答案

你的代码对我有用。如果我像这样启动服务器:

sudo python server.py

然后发送如下消息:

echo this is a test | nc -u localhost 514

我在标准输出上看到输出:

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

文件 youlogfile.log 包含:

this is a test

我怀疑您的问题源于尝试使用 TCP 工具连接到 UDP 服务器。

关于用于网络设备的 Python Syslog 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823587/

相关文章:

python - 向量化 numpy 对于子数组是唯一的

python - 在python中制作日期转换器的问题

sockets - 为什么在 TCP 中使用 bind()?为什么它只用在服务器端而不用在客户端?

c - 最新的系统日志消息被延迟

python - 如何在 Xcode 中将 Python 函数导入 C?

python - 如何在 docker 入口点内运行导出命令?

sockets - TCP 套接字是否需要有线连接?

C# 多线程和套接字问题

c - 系统日志不记录我的程序日志条目

syslog - 系统日志的 Fluentd 无效时间格式