我有一個我想分析的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]
我有一個我想分析的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]
您可以使用正則表達式實現它。嘗試下面
#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
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']
這可以通過使用正則表達式來實現:
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')]
(我所做的輸出相匹配的描述,而不是你的榜樣輸出完全匹配其我完全不明白)。
我認爲你需要這樣的正則表達式。 – egon12
@Ted Brown:檢查答案並提供反饋 –
你的示例輸出不僅僅是IP地址 - 末尾有'.38'和'.80'位? – spookylukey