import pyshark def NetCap(iface,file,pkt_count): print ('capturing...') livecapture = pyshark.LiveCapture(interface=iface, output_file=file) livecapture.sniff(packet_count=pkt_count)#timeout=10) print ('end of capture.') print (livecapture) #for pkt in livecapture: # print (pkt) def ReadCapFile(sFile): cap = pyshark.FileCapture(sFile) for pkt in cap: print (pkt) def capture_live_packets(network_interface): capture = pyshark.LiveCapture(interface=network_interface) for raw_packet in capture.sniff_continuously(): if(raw_packet!=None): #print(filter_all_tcp_traffic_file(raw_packet)) ##Stampa solo i pacchetti tcp print(raw_packet)#filter_all_tcp_traffic_file(raw_packet)) def get_packet_details(packet): """ This function is designed to parse specific details from an individual packet. :param packet: raw packet from either a pcap file or via live capture using TShark :return: specific packet details """ protocol = packet.transport_layer if hasattr(packet, 'ip'): source_address = packet.ip.src else: source_address ="???.???.???.???" source_port = packet[packet.transport_layer].srcport #destination_address = packet.ip.dst if hasattr(packet, 'ip'): destination_address = packet.ip.src else: destination_address ="???.???.???.???" destination_port = packet[packet.transport_layer].dstport packet_time = packet.sniff_time return f'Packet Timestamp: {packet_time}' \ f'\nProtocol type: {protocol}' \ f'\nSource address: {source_address}' \ f'\nSource port: {source_port}' \ f'\nDestination address: {destination_address}' \ f'\nDestination port: {destination_port}\n' def filter_all_tcp_traffic_file(packet): """ This function is designed to parse all the Transmission Control Protocol(TCP) packets :param packet: raw packet :return: specific packet details """ if hasattr(packet, 'tcp'): results = get_packet_details(packet) return results def dump(iface): capture = pyshark.LiveCapture(interface=iface) for packet in capture: if 'ETH Layer' in str(packet.layers): field_names = packet.eth._all_fields field_values = packet.eth._all_fields.values() for field_name, field_value in zip(field_names, field_values): print(f'{field_name}: {field_value}') if __name__ == "__main__": IFace="Wi-Fi"#"Ethernet 3"#"\\Device\\NPF_{56958110-5378-4478-945F-4795551A47CC}" ###Cattura 10 Pkt e salva su file: #NetCap(IFace,file='./test.pcapng',pkt_count=10) #ReadCapFile('./test.pcapng') ###live capture #capture_live_packets(IFace) dump(IFace)