How to save tshark statistics in variables

﹥>﹥吖頭↗ 提交于 2019-12-04 14:43:04

问题


I would like to save the output of a tshark command in a variable.

For example if I run:

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

I will get :

Time            |frames|  bytes

00.000-060.000     742     51660

I want to save the total number of frames in a variable in my script for further calculations.


回答1:


First save the output to a file :

Either by running this command in shell:

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

Or use subprocess.Popen():

from subprocess import Popen

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

Now open the file and calculate the total number of frames:

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



回答2:


On my system tshark's output format differs from the one you've shown in the question. To make parsing more robust, I've changed the command-line:

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

You don't need to call tshark to get statistics from a pcap file. You could use a Python library that can parse pcap files e.g., using scapy:

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

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

To get count for tshark -r capture.pcap -qz 'io,stat,0,ip.src==192.168.230.146' command using 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)


来源:https://stackoverflow.com/questions/14451599/how-to-save-tshark-statistics-in-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!