用于网络设备的Python系统日志服务器
为我的网络设备创建一个python系统日志服务器,我使用下面的代码 这将满足我的需要,但我似乎无法运行任何python版本的sysloghandler。我看到这是大约5年前的老代码。 我正在运行ubuntu 16.04系统。一切似乎都取决于尝试:启动服务器用于网络设备的Python系统日志服务器,python,sockets,syslog,Python,Sockets,Syslog,为我的网络设备创建一个python系统日志服务器,我使用下面的代码 这将满足我的需要,但我似乎无法运行任何python版本的sysloghandler。我看到这是大约5年前的老代码。 我正在运行ubuntu 16.04系统。一切似乎都取决于尝试:启动服务器 #!/usr/bin/env python ## Tiny Syslog Server in Python. ## ## This is a tiny syslog server that is able to receive UDP b
#!/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
然后发送如下消息:
sudo python server.py
echo this is a test | nc -u localhost 514
我在stdout上看到了输出:
('127.0.0.1 : ', 'this is a test')
文件youlogfile.log
包含:
this is a test
我怀疑您的问题源于尝试使用TCP工具连接到UDP服务器。您是否在
netstat
输出中看到侦听绑定?否,并且当我尝试在端口514上本地或远程使用telnet进行连接时,它不会应答较低的端口受系统保护。请尝试将服务器绑定到端口5144,这可能会有所帮助,但我不确定这是您遇到的问题Syslog通过udp而不是tcp运行,因此即使在它工作时,您也无法远程登录到它。如果您使用的是python3,请将SocketServer
更改为SocketServer
。官方参考在这里是一个很好的教训,通常是一些容易被忽略的东西。您通常也有记录器
命令<代码>记录器-d-n 127.0.0.1-P 514“foobar”。注意!我真的会为自定义记录器选择514以外的另一个端口,因为514很可能会被您的“真正”系统日志守护进程占用。