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.
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
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)