from scapy.all import *
import csv
import socket
def capture_and_save_packets(filter, count, filename):
try:
# Start the capture
packets = sniff(filter=filter, count=count)
except Exception as e:
print(f"An error occurred while capturing packets: {e}")
return None
try:
# Open a CSV file to store the packets
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
# Write the header row
writer.writerow(["Source", "Destination", "Protocol", "Service", "Duration",
"Src_to_Dst_Bytes", "Dst_to_Src_Bytes", "Src_to_Dst_TTL", "Dst_to_Src_TTL",
"Src_Retransmitted", "Dst_Retransmitted", "Src_Dropped", "Dst_Dropped"])
# Write the packets to the CSV file
for packet in packets:
service = None
src_to_dst_bytes = 0
dst_to_src_bytes = 0
src_to_dst_ttl = 0
dst_to_src_ttl = 0
src_retransmitted = 0
dst_retransmitted = 0
src_dropped = 0
dst_dropped = 0
if IP in packet:
src = packet[IP].src
dst = packet[IP].dst
proto = packet[IP].proto
ttl = packet[IP].ttl
duration = packet.time
if TCP in packet:
service = packet[TCP].dport
src_to_dst_bytes = packet[TCP].payload.len
dst_to_src_bytes = (packet[TCP].ack - packet[TCP].seq) #- packet[TCP].payload.len
if "E" in packet[TCP].flags:
src_retransmitted = 1
if "R" in packet[TCP].flags:
dst_retransmitted = 1
if "D" in packet[TCP].flags:
src_dropped = 1
if "F" in packet[TCP].flags:
dst_dropped = 1
elif UDP in packet:
service = packet[UDP].dport
src_to_dst_bytes = packet[UDP].len
dst_to_src_bytes = len(packet) - len(packet[UDP])
if packet[UDP].chksum == None:
src_retransmitted = 1
dst_retransmitted = 1
src_dropped = 1
dst_dropped = 1
writer.writerow([src, dst, proto, service, duration,
src_to_dst_bytes, dst_to_src_bytes, src_to_dst_ttl, dst_to_src_ttl,
src_retransmitted, dst_retransmitted, src_dropped, dst_dropped])
except Exception as e:
print(f"An error occurred while saving the packets to a CSV file: {e}")
return None
print("Packets captured and saved to CSV file successfully.")
return packets
#Define the filter for the packets you want to capture
filter = "host 192.168.8.102"
#Call the capture_and_save_packets function
packets = capture_and_save_packets(filter, 10 ,"packets.csv")
#print packets to the console
if packets:
for packet in packets:
print(packet)
我想捕获数据并将其保存在 csv 文件中,但此错误不断出现