从PCAP文件中提取时间并另存为CSV文件

时间:2019-04-14 13:42:25

标签: python timestamp arp dpkt

我只想为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(数据包,文件名,tcp,ts,度排序):       使用open(filename,'w')as f:         对于数据包中的数据包:           数据=''           对于包装中的物品:             数据=数据+ str(项目)+','           f.write(data + tcp + datetime.datetime.utcfromtimestamp(ts).strftime(“%m /%d /%Y,%H:%M:%S”)+ degree_sorted +'\ n')

1 个答案:

答案 0 :(得分: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")))