为我的网络设备创建一个 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/