You need to enable JavaScript to run this app. pyshark指定-c参数抓包数量超出预期问题求助
优惠活动
大模型
产品
解决方案
定价
更多

pyshark指定-c参数抓包数量超出预期问题求助

问题描述

执行命令python python.py -i eth0 -c 10时,预期捕获10个数据包后程序自动退出,但实际捕获并打印了远超指定数量的数据包,原代码如下:

#!/usr/bin/python

import argparse
import pyshark
import time
import re as regex


parser = argparse.ArgumentParser()
parser.add_argument('-i', '--interface', metavar=" ", type=str, required = True, help = 'To specify the interface ')
parser.add_argument('-v', '--verbose', required = False, action = 'store_true', help = 'To print the all layer of packet')
parser.add_argument('-o', '--output', metavar=' ', help = 'To capture and save the pcap in a file')
parser.add_argument('-p', '--protocol', metavar=' ', help= 'To capture packet using ptotocl filter')
parser.add_argument('-u', '--udp', action = 'store_true', help = 'To capture udp packet only')
parser.add_argument('-t', '--tcp', action = 'store_true', help = 'To capture tcp packet only')
parser.add_argument('-c', '--count', metavar=' ',type=int, default=1,  help = 'To capture limited number of packet')

args = parser.parse_args()

if args.count:
   capture = pyshark.LiveCapture(interface=args.interface)
   capture.sniff(packet_count = args.count)

elif args.protocol:
   capture = pyshark.LiveCapture(interface=args.interface, display_filter=args.protocol)


elif args.udp:
   capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='udp')

elif args.tcp:
   capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='tcp')

else:
   capture = pyshark.LiveCapture(interface=args.interface, output_file=args.output)
#   capture.sniff(packet_count = args.count)

packet_list = []

for packet in capture.sniff_continuously():
    if 'IP Layer' in str(packet.layers):
        protocol = regex.search(r'(Protocol:)(.*)',str(packet.ip))
        protocol_type = protocol.group(2).strip().split(' ')[0]
       # proto = protocol_type
    localtime = time.asctime(time.localtime(time.time())) 
    proto = protocol_type
    src_addr = packet.ip.src
    dst_addr = packet.ip.dst
    length = packet.length
    print (localtime, '\t' , proto, '\t' ,src_addr, '\t', dst_addr, '\t' , length)
    if args.verbose:
       print(packet.show())
问题根源
  • 重复捕获逻辑冲突:当使用-c参数时,代码先调用capture.sniff(packet_count=args.count)捕获了指定数量的数据包,但后续又调用capture.sniff_continuously()——这个方法会持续捕获数据包直到手动终止程序,直接导致超出指定数量的数据包被处理。
  • 分支逻辑设计缺陷:if args.count分支仅执行了一次有限捕获,但后续的遍历逻辑完全忽略了计数限制,无限制地处理新捕获的数据包。
  • 捕获对象复用问题:同一个capture对象被先后用于两次捕获操作,第一次的有限捕获完成后,第二次的sniff_continuously()会重新启动无限制捕获流程。
修复方案

统一捕获逻辑,让计数参数能正确限制数据包数量,同时增加异常防护避免程序崩溃,修改后的代码如下:

#!/usr/bin/python

import argparse
import pyshark
import time
import re as regex


parser = argparse.ArgumentParser()
parser.add_argument('-i', '--interface', metavar=" ", type=str, required=True, help='To specify the interface ')
parser.add_argument('-v', '--verbose', required=False, action='store_true', help='To print all layers of packet')
parser.add_argument('-o', '--output', metavar=' ', help='To capture and save the pcap in a file')
parser.add_argument('-p', '--protocol', metavar=' ', help='To capture packets using protocol filter')
parser.add_argument('-u', '--udp', action='store_true', help='To capture udp packets only')
parser.add_argument('-t', '--tcp', action='store_true', help='To capture tcp packets only')
parser.add_argument('-c', '--count', metavar=' ', type=int, default=1, help='To capture limited number of packets')

args = parser.parse_args()

# 根据参数初始化捕获对象
capture_config = {'interface': args.interface}
if args.output:
    capture_config['output_file'] = args.output
if args.protocol:
    capture_config['display_filter'] = args.protocol
elif args.udp:
    capture_config['bpf_filter'] = 'udp'
elif args.tcp:
    capture_config['bpf_filter'] = 'tcp'

capture = pyshark.LiveCapture(**capture_config)

# 捕获指定数量的数据包
captured_packets = capture.sniff(packet_count=args.count)

# 遍历处理捕获到的数据包
for packet in captured_packets:
    protocol_type = 'Unknown'
    src_addr = 'N/A'
    dst_addr = 'N/A'
    
    if 'IP Layer' in str(packet.layers):
        protocol_match = regex.search(r'(Protocol:)(.*)', str(packet.ip))
        if protocol_match:
            protocol_type = protocol_match.group(2).strip().split(' ')[0]
        src_addr = packet.ip.src
        dst_addr = packet.ip.dst
    
    localtime = time.asctime(time.localtime(time.time()))
    print(localtime, '\t', protocol_type, '\t', src_addr, '\t', dst_addr, '\t', packet.length)
    
    if args.verbose:
        print(packet.show())

修复说明

  1. 统一捕获流程:先根据所有参数配置LiveCapture对象,再通过sniff(packet_count=args.count)一次性获取指定数量的数据包,避免重复捕获操作。
  2. 增加异常防护:对非IP数据包和协议匹配失败的情况做了兼容处理,避免程序因属性不存在报错。
  3. 移除冗余逻辑:删除了导致持续捕获的sniff_continuously()调用,改为直接遍历已捕获的数据包列表,确保处理数量严格符合-c参数的设置。

内容的提问来源于stack exchange,提问作者user20828450

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:45:23