如何在变量中保存tshark统计信息

时间:2013-01-22 04:28:42

标签: python wireshark tshark

我想将tshark命令的输出保存在变量中。

例如,如果我跑:

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

我会得到:

Time            |frames|  bytes

00.000-060.000     742     51660

我想在脚本中保存变量中的帧总数,以便进一步计算。

2 个答案:

答案 0 :(得分:1)

首先将输出保存到文件中:

在shell中运行此命令:

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 :(得分: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文件中获取统计信息。您可以使用可以解析pcap文件的Python库,例如,使用scapy

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

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

使用tshark -r capture.pcap -qz 'io,stat,0,ip.src==192.168.230.146'计算scapy命令:

#!/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)