使用 Python 将防火墙 Syslog Entires 中的结构化字符串数据解析为 dict

Tho*_*ard 2 python string dictionary python-3.x

我有一个结构化字符串通过套接字输入到我的 Python 脚本中,该脚本能够从网络上的另一个项目接收 UDP 系统日志数据。该字符串的格式如下:

<30>device="SFW" date=2019-03-07 time=11:12:19 timezone="EST" device_name="SFV4C6" device_id=C12345678ABCXYZ log_id=063110617710 log_type="Event" log_component="SSL VPN Authentication" log_subtype="Authentication" status="Successful" priority=Information user_name="valid@username" usergroupname="" auth_client="N/A" auth_mechanism="AD" reason="" src_ip=123.234.123.234 message="User valid@username authenticated successfully to login to SSLVPN through AD authentication mechanism" name="" src_mac=
<30>device="SFW" date=2019-03-07 time=11:12:20 timezone="EST" device_name="SFV4C6" device_id=C12345678ABCXYZ log_id=062910617701 log_type="Event" log_component="Firewall Authentication" log_subtype="Authentication" status="Successful" priority=Information user_name="valid@username" usergroupname="vpnallaccess" auth_client="SSLVPN" auth_mechanism="" reason="" src_ip=10.1.250.123 message="User valid@username of group vpnallaccess logged in successfully to Firewall through  authentication mechanism from 10.1.250.3" name="User Name" src_mac=
Run Code Online (Sandbox Code Playgroud)

...字符串中有许多键值对。(请注意,key= otherkey=something如果为空,则有效,显然,对于此防火墙的系统日志实现,它key=会被解释为)key=None

我一生都没有弄清楚如何正确地将其拆分以将键值对放入 Python 中的 dict 文件中。简单地按空格分割是行不通的,因为某些双引号字符串包含空格。

有没有人有一种巧妙的方法来拆分数据并将其解析为 dict 对象,以便我可以直接引用其中的日志值,而不必每次使用长正则表达式等不断地从字符串中拆分出特定数据?

Aus*_*tin 5

shlex为您做的工作:

import shlex

s = '<30>device="SFW" date=2019-03-07 time=10:59:05 timezone="EST" device_name="SF4C6" log_component="SSL VPN Authentication"'

print({x: y for x, y in map(lambda x: x.split('='), shlex.split(s))})
# {'<30>device': 'SFW', 'date': '2019-03-07', 'time': '10:59:05', 'timezone': 'EST', 'device_name': 'SF4C6', 'log_component': 'SSL VPN Authentication'}
Run Code Online (Sandbox Code Playgroud)

  • 这是你发现/使用的某种***邪恶的黑魔法***!但它完全按照我需要的方式工作!非常感谢你!我喜欢在这里使用“lambda”来进一步处理键值对的映射,很好!(我很少使用 lambda 函数,但我总是忘记它们有多有用!) (2认同)