Skip to main content
 首页 » 编程设计

python之从 header 和部分有效负载中提取内容

2025年05月04日23pander-it

data.log 文件中有以下内容。我希望提取 ts 值和部分有效负载(在有效负载中的 deadbeef 之后,第三行,从倒数第二个字节开始。请引用预期输出)。

数据.log

print 1: file offset 0x0 
ts=0x584819041ff529e0 2016-12-07 14:13:24.124834649 UTC 
type: ERF Ethernet 
dserror=0 rxerror=0 trunc=0 vlen=0 iface=1 rlen=96 lctr=0 wlen=68 
pad=0x00 offset=0x00 
dst=aa:bb:cc:dd:ee:ff src=ca:fe:ba:be:ca:fe 
etype=0x0800 
45 00 00 32 00 00 40 00 40 11 50 ff c0 a8 34 35         E..2..@.@.P...45 
c0 a8 34 36 80 01 00 00 00 1e 00 00 08 08 08 08         ..46............ 
08 08 50 e6 61 c3 85 21 01 00 de ad be ef 85 d7         ..P.a..!........ 
91 21 6f 9a 32 94 fd 07 01 00 de ad be ef 85 d7         .!o.2........... 
 
 
print 2: file offset 0x60 
ts=0x584819041ff52b00 2016-12-07 14:13:24.124834716 UTC 
type: ERF Ethernet 
dserror=0 rxerror=0 trunc=0 vlen=0 iface=1 rlen=96 lctr=0 wlen=68 
pad=0x00 offset=0x00 
dst=aa:bb:cc:dd:ee:ff src=ca:fe:ba:be:ca:fe 
etype=0x0800 
45 00 00 32 00 00 40 00 40 11 50 ff c0 a8 34 35         E..2..@.@.P...45 
c0 a8 34 36 80 01 00 00 00 1e 00 00 08 08 08 08         ..46............ 
08 08 68 e7 61 c3 85 21 01 00 de ad be ef 86 d7         ..h.a..!........ 
91 21 c5 34 77 bd fd 07 01 00 de ad be ef 86 d7         .!.4w........... 
 
print 3806: file offset 0x592e0 
ts=0x584819042006b840 2016-12-07 14:13:24.125102535 UTC 
type: ERF Ethernet 
dserror=0 rxerror=0 trunc=0 vlen=0 iface=1 rlen=96 lctr=0 wlen=68 
pad=0x00 offset=0x00 
dst=aa:bb:cc:dd:ee:ff src=ca:fe:ba:be:ca:fe 
etype=0x0800 
45 00 00 32 00 00 40 00 40 11 50 ff c0 a8 34 35         E..2..@.@.P...45 
c0 a8 34 36 80 01 00 00 00 1e 00 00 08 08 08 08         ..46............ 
08 08 50 74 73 c3 85 21 01 00 de ad be ef 62 e6         ..Pts..!......b. 
91 21 ed 4a 8c df fd 07 01 00 de ad be ef 62 e6         .!.J..........b. 

我的预期输出

0x584819041ff529e0,85d79121 
0x584819041ff52b00,86d79121 
0x584819042006b840,62e69121 

到目前为止我尝试了什么

我能够提取 ts 值。我用过

 awk -v ORS="" '$NF == "UTC"{print sep$1; sep=","} END{print "\n"}' data.log 
 >> ts=0x584819041ff529e0,ts=0x584819041ff52b00 

但未能成功提取有效负载内容。

非常感谢任何帮助。

请您参考如下方法:

这是完成它的一种方法:

awk -F '=| ' '/^ts=/{printf $2","} /de ad be ef/{if(!a){printf $15$16;a=1}else{print $1$2;a=0}}' data.log 

输出:

0x584819041ff529e0,85d79121 
0x584819041ff52b00,86d79121 

解释:

-F '=| '                 : set the field seperator to both '=' and 'space' 
/^ts=/{printf $2","}     : if pattern 'ts=' found at line beginning, print the second field 
/de ad be ef/{something} : if pattern 'de ad be ef' found, do 'something' 

初始变量 a 将等于 0。如果模式 de ad be ef 是第一次被发现,if(!a) 将成功并因此打印 15th 和 第 16 个 字段。现在将 a 设置为 1。因此,当 de ad be ef 模式在下一行中匹配时,if(!a) 检查将失败,因此打印 1st 和 2nd 字段。现在,将 a 重置为 0 并对文件的其余部分继续相同的过程。