I want to capture the limited number of packet. for example, while I am using the command python python.py -I eth0 -c 10 then I wan to capture only 10 number of packet and exit but I am printing many packets instead of 10. please tell me where am I wrong.
#!/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())
output
I am capturing more than 10 packets.