Search code examples
pythonscapy

How do I write the data from Scapy into a CSV file


Using Scapy I have extracted the ethernet frame length, IP payload size, and the header length I would like to write this information to a csv file for further examination

from scapy.all import *

pcap = rdpcap('example.pcap')
out = open("out.csv", "wb")

for pkts in pcap:
    ethernet_header = (len(pkts)) # IP payload size
    ip_pload = (len(pkts.payload) - 20) # Ethernet frame length
    ip_header = (len(pkts.payload)) # Total length IP header
    print(ip_pload, len(pkts), ip_header)

    out.write(ethernet_header, ip_pload, ip_header)



Solution

  • Use the builtin csv.writer, it's quite easy to use:

    import csv
    with open('out.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        for pkts in pcap:
            ethernet_header = (len(pkts)) # IP payload size
            ip_pload = (len(pkts.payload) - 20) # Ethernet frame length
            ip_header = (len(pkts.payload)) # Total length IP header
            writer.writerow([ethernet_header, ip_pload, ip_header])