2017-10-29 297 views
0

我有一个我想分析的tcpdump文件。 tcpdump的文件看起来像这样如何用python解析tcpdump文件

23:31:54.380799 IP 192.140.3.20.38373 > 240.240.255.250.8082: UDP, length 542 

我想分析该文件以获得源IP,目的IP和分组的总大小,并将其存储到一个列表。

我怎样才能得到的输出是这个样子:

[192.140.3.20.38,240.240.255.250.80,542] 
+0

我认为你需要这样的正则表达式。 – egon12

+0

@Ted Brown:检查答案并提供反馈 –

+0

你的示例输出不仅仅是IP地址 - 末尾有'.38'和'.80'位? – spookylukey

回答

0

您可以使用正则表达式实现它。尝试下面

#Take the value in a string 
string = """23:31:54.380799 IP 192.140.3.20.38373 > 240.240.255.250.8082: UDP, length 542""" 

#import regular expression module 
import re 



#Retrieve source and destination ip 
output = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", string) 

#packet size 
output.append(re.sub(r'.*length(.*)',r'\1',string)) 

#required info is in output 


print output 
0

pyparsing往往被忽视写作解析器的一种方式,可以是具有很强的可读性 - 快。

在这种情况下,time代表每个tcpdump行开头的语法元素。 address代表每个TCP地址。例如,pp.Literal被各种用于呈现诸如“IP”和“>”的粒子。我用suppress方法省略了输出中不需要的项目。

我已经处理的文件是您的行重复了大约十次,只有最后一个常数在每行中递增。

>>> import pyparsing as pp 
>>> time = pp.Word(pp.nums + '.:') 
>>> address = pp.Word(pp.nums + '.') 
>>> line = time.suppress() + pp.Literal('IP').suppress() + address + pp.Literal('>').suppress() + address + pp.Literal(':').suppress() + pp.Literal('UDP,').suppress() + pp.Literal('length').suppress() + pp.Word(pp.nums) 
>>> with open('temp.txt') as lines: 
...  for a_line in lines: 
...   print (line.parseString(a_line).asList()) 
...   
['192.140.3.20.38373', '240.240.255.250.8082', '542'] 
['192.140.3.20.38373', '240.240.255.250.8082', '543'] 
['192.140.3.20.38373', '240.240.255.250.8082', '544'] 
['192.140.3.20.38373', '240.240.255.250.8082', '545'] 
['192.140.3.20.38373', '240.240.255.250.8082', '546'] 
['192.140.3.20.38373', '240.240.255.250.8082', '547'] 
['192.140.3.20.38373', '240.240.255.250.8082', '548'] 
['192.140.3.20.38373', '240.240.255.250.8082', '549'] 
['192.140.3.20.38373', '240.240.255.250.8082', '550'] 
0

这可以通过使用正则表达式来实现:

import re 
data = "23:31:54.380799 IP 192.140.3.20.38373 > 240.240.255.250.8082: UDP, length 542\n" * 2 
print(re.findall(r"[^ ]* IP (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).\d+ > (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).\d+:.*, length (\d+)", data)) 

输出:

[('192.140.3.20', '240.240.255.250', '542'), 
('192.140.3.20', '240.240.255.250', '542')] 

(我所做的输出相匹配的描述,而不是你的榜样输出完全匹配其我完全不明白)。