1

我只想从 ARP 数据包的 PCAP 文件中提取日期时间,并希望保存为 csv/txt。我确实使用下面的代码来提取时间。打印命令随着时间的推移工作正常。但是当它保存在 csv 文件中时,它只有一个日期和一次(例如 14:59:58)保存到 csv 文件中。任何人都可以建议修改从 pcap 中提取 ARP 时间并正确保存到 csv 的代码。谢谢你。

使用 open("../data/" + 文件名 + ".pcap", 'rb') 作为 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 packet: 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')

4

1 回答 1

0
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")))
于 2019-04-14T14:10:32.653 回答