如何在变量中保存 tshark 统计信息 [英] How to save tshark statistics in variables

查看:31
本文介绍了如何在变量中保存 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)

这篇关于如何在变量中保存 tshark 统计信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆