Python socket模拟UDP采集器
1. 代码实现
#syslog_receiver.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import logging
import socket
log = logging.getLogger('udp_server')
def udp_server(host='0.0.0.0', port=514):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
log.info("Listening on udp %s:%s" % (host, port))
s.bind((host, port))
while True:
(data, addr) = s.recvfrom(128 * 1024)
yield data.decode("utf-8")
FORMAT_CONS = '%(asctime)s %(name)-12s %(levelname)8s\t%(message)s'
logging.basicConfig(level=logging.DEBUG, format=FORMAT_CONS, filename='syslog.log')
for data in udp_server():
log.debug("%r" % (data,))
1.2 调试
2022-04-12 17:39:54,748 udp_server INFO Listening on udp 0.0.0.0:514
2022-04-12 17:40:14,050 udp_server DEBUG '采集数据'
2022-04-12 17:40:14,057 udp_server DEBUG '采集数据'
2. 总结
利用Python脚本简单地模拟网络安全监测装置,对待采集对象,收集其采集对象设备名、ip、mac地址等信息。