2013-01-22 85 views
1

我想將tshark命令的輸出保存在一個變量中。如何在變量中保存tshark統計信息

例如,如果我運行:

tshark -r capture.pcap -qz io,stat,0 

我會得到:

Time   |frames| bytes 

00.000-060.000  742  51660 

我想保存在我進一步計算腳本變量幀的總數。

回答

1

首先輸出保存到一個文件:

通過運行在外殼下面的命令:

tshark -r capture.pcap -qz io,stat,0 > abc.txt

或者使用subprocess.Popen()

from subprocess import Popen 

with open("abc.txt","w") as f: 
    Popen(["tshark" ,"-r","capture.pcap","-qz", "io,stat,0"],stdout=f) 

現在打開該文件,計算總幀數:

with open("abc.txt") as f: 
    next(f) #skip header 
    tot_frames=sum(int(line.split()[1]) for line in f if line.strip()) 
    print (tot_frames)   #prints 742 
1

在我的系統上tshark的輸出格式與您在問題中顯示的格式不同。 爲了使解析更加強勁,我已經改變了命令行:

#!/usr/bin/env python 
import shlex 
from itertools import dropwhile 
from subprocess import check_output as qx 

# get tshark output 
command = "tshark -r capture.pcap -qz 'io,stat,0,COUNT(frame)frame'" 
lines = qx(shlex.split(command)).splitlines() 

# parse output 
lines = dropwhile(lambda line: not line.rstrip().endswith("COUNT"), lines) 
next(lines) # skip header 
frames_count = int(next(lines).split()[1]) 
print(frames_count) 

你並不需要調用tshark從PCAP文件中獲取的統計數據。你可以使用一個Python庫,可以分析PCAP文件例如,使用scapy

#!/usr/bin/env python 
from scapy.all import rdpcap 

a = rdpcap('capture.pcap') 
frames_count = len(a) 
print(frames_count) 

要獲得計數使用scapytshark -r capture.pcap -qz 'io,stat,0,ip.src==192.168.230.146'命令:

#!/usr/bin/env python 
from scapy.all import IP, sniff 

a = sniff(offline='capture.pcap', 
      lfilter=lambda p: IP in p and p[IP].src == '192.168.230.146') 
count = len(a) 
print(count) 
+0

我認爲第一個解決方案是一個更好的方式,我想要找出來自每個源的接收數據包的數量。所以命令將是:「tshark -r capture.pcap -qz'io,stat,0,ip.src == 192.168.230.146」。在這種情況下,我需要像你一樣解析輸出。 scapy能夠基於src或dst進行過濾嗎? – samaneh

+0

是的。 'count = len(a.filter(lambda pkt:pkt ['IP']。src =='192.168.230.146'))' – jfs

+0

@samaneh:你可以結合加載和過濾:'count = len(sniff(offline ='capture.pcap',lfilter = lambda p:p [IP] .src =='192.168.230.146'))',添加'from scapy.all import IP,sniff' before。 – jfs