0
votes

I would like to extract date time from PCAP files only for ARP packets and would like to save as csv/txt. i did uses below code for extract time. print command is working fine with time. but when its save at csv file its only one date and one time (example 14:59:58) save in to csv file. can any one suggest for modify the codes for extract ARP times from pcap and save to csv CORRECTLY. Thank you.

with open("../data/" + filename + ".pcap", 'rb') as f: pcap = dpkt.pcap.Reader(f)

    requests = []
    replies = []

    for ts, buf in pcap:

        eth = dpkt.ethernet.Ethernet(buf)
        # If the packet is not arp

        if eth.type != 2054:
            continue
        try:
            arp = eth.arp
        except Exception as e:
            continue

        src = dpkt.socket.inet_ntoa(arp.spa)
        tgt = dpkt.socket.inet_ntoa(arp.tpa)

        if arp.op == 2:
            count_duplication(replies, src, tgt)

        elif arp.op == 1:
            count_duplication(requests, src, tgt)


        packet_time = datetime.datetime.utcfromtimestamp(ts).strftime("%m/%d/%Y, %H:%M:%S")

        print (packet_time)

  save_packets(sorted(requests, key=lambda x: -x[2]), '../tmp/count-requests-xyz' + '.csv', packet_time)

# Save Packets

def save_packets(packets,filename,tcp,ts, degree_sorted): with open(filename, 'w') as f: for packet in packets: data = '' for item in packet: data = data + str(item) + ',' f.write(data + tcp + datetime.datetime.utcfromtimestamp(ts).strftime("%m/%d/%Y, %H:%M:%S") + degree_sorted + '\n')

1
Explain the desired csv structure. Do you know how to find ARP only packets?balderman
CSV files will contain src_ip,dst_ip, number of packets, time................and yes i know how to extract ARP only packets, I already extracted as per required features.delwar.naist

1 Answers

0
votes
import socket
import datetime
import dpkt


def _inet_to_str(inet):
    try:
        return socket.inet_ntop(socket.AF_INET, inet)
    except ValueError:
        return socket.inet_ntop(socket.AF_INET6, inet)


def arp(pcap_path):
    def _is_arp(packet):
        return True

    with open(pcap_path, 'rb') as f:
        pcap = dpkt.pcap.Reader(f)
        for ts, buf in pcap:
            eth = dpkt.ethernet.Ethernet(buf)
            if not isinstance(eth.data, dpkt.ip.IP):
                continue

            if not _is_arp(eth):
                continue
            ip = eth.data
            # write to file instead of printing
            print('{},{},{}'.format(_inet_to_str(ip.src), _inet_to_str(ip.dst),
                                    datetime.datetime.utcfromtimestamp(ts).strftime("%m/%d/%Y, %H:%M:%S")))