如何在变量中保存 tshark 统计信息
我想将 tshark
命令的输出保存在一个变量中.
I would like to save the output of a tshark
command in a variable.
例如,如果我运行:
tshark -r capture.pcap -qz io,stat,0
我会得到:
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.
在我的系统上 tshark
的输出格式与您在问题中显示的格式不同.为了使解析更加健壮,我更改了命令行:
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)
您无需调用 tshark
即可从 pcap 文件中获取统计信息.您可以使用可以解析 pcap 文件的 Python 库,例如,使用 scapy
:
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)
使用 scapy
获取 tshark -r capture.pcap -qz 'io,stat,0,ip.src==192.168.230.146'
命令的计数:
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)