从txt文件中提取tcpdump时间戳

时间:2014-10-29 16:38:21

标签: python parsing tcpdump

我正在尝试使用python从tcpdump的输出计算吞吐量。到目前为止,我从python调用tcpdump并设法将输出写入文本文件。样本输出:

01:06:23.649464 0us IP(tos 0x0,ttl 128,id 63533,offset 0,flags [none],proto UDP(17),length 72)251.146.199.137.1066> 156.96.135.220.62827:UDP,长度44

01:06:23.920316 0us IP(tos 0x0,ttl 1,id 10354,offset 0,flags [none],proto IGMP(2),length 32,options(RA))251.146.198.120> fm-dyn-140-0-193-221.fast.net.id: [| igmp]

然而,我坚持下一部分。提取时间和长度(第一个)并计算吞吐量。我是python的新手,对正则表达式一无所知。此外,由于时间戳包括微秒,是否有任何简单的方法与它们一起计算吞吐量?

提前致谢。

1 个答案:

答案 0 :(得分:0)

忘记正则表达式,你可以使用datetime模块。

使用datetime

>>> from datetime import datetime
>>> lines = ['01:06:23.649464 0us IP (tos 0x0, ttl 128, id 63533, offset 0, flags [none], proto UDP (17), length 72) 251.146.199.137.1066 > 156.96.135.220.62827: UDP, length 44', '01:06:23.920316 0us IP (tos 0x0, ttl 1, id 10354, offset 0, flags [none], proto IGMP (2), length 32, options (RA)) 251.146.198.120 > fm-dyn-140-0-193-221.fast.net.id: [|igmp]']
>>> times = [datetime.strptime(line[:15], '%H:%M:%S.%f') for line in lines]

可以直接计算吞吐量,但您需要使用strptime中的datetime

>>> times[1] - times[0]
datetime.timedelta(0, 0, 270852)
相关问题