1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | from pylibpcap.pcap import rpcap import struct from dpkt.pcap import Reader from scapy.all import rdpcap #from scapy.all import PcapReader import pyshark from timeit import repeat import time fileName = "/Users/microfat/Downloads/new/N1N2.pcap" def libpcap_test(): for _, _, packet in rpcap(fileName): pass def orig_test(): string_data = None with open(fileName, 'rb') as fpcap: string_data = fpcap.read() packet_num = 0 packet_data = [] i =24 while(i<len(string_data)): packet_len = struct.unpack('I',string_data[i+12:i+16])[0] packet_data.append(string_data[i+16:i+16+packet_len]) i = i+ packet_len+16 packet_num+=1 for packet in packet_data: pass def dpkt_test(): with open(fileName, 'rb') as f: for _, packet in Reader(f): pass def scapy_test(): for packet in rdpcap(fileName): pass def pyshark_test(): cap = pyshark.FileCapture(fileName, use_json=True, include_raw=True) for packet in cap: packet.get_raw_packet() if __name__ == "__main__": libpcap_test_time = repeat(stmt=libpcap_test, repeat=100, number=1) time.sleep(1) orig_test_time = repeat(stmt=orig_test, repeat=100, number=1) time.sleep(1) dpkt_test_time = repeat(stmt=dpkt_test, repeat=100, number=1) time.sleep(1) scapy_test_time = repeat(stmt=scapy_test, repeat=100, number=1) time.sleep(1) pyshark_test_time = repeat(stmt=pyshark_test, repeat=100, number=1) print('libpcap:', sum(libpcap_test_time)/len(libpcap_test_time)) print('orig: ', sum(orig_test_time)/len(orig_test_time)) print('dpkt: ', sum(dpkt_test_time)/len(dpkt_test_time)) print('scapy: ', sum(scapy_test_time)/len(scapy_test_time)) print('pyshark:', sum(pyshark_test_time)/len(pyshark_test_time)) |
1 2 3 4 5 | libpcap: 0.00011515187999975751 orig: 0.0005123037399994246 dpkt: 0.0010648190799918212 scapy: 0.05218072557000596 pyshark: 0.7941113060799978 |
结论:
libpcap > struct > dpkt > scapy > pyshark
pylibpcap由于使用到了Cython libpcap,因而速度非常快
但在功能易用性上来说大致是相反的结论
参考:https://stackoverflow.com/a/56119892