在csv文件python中打印输出

时间:2016-02-09 06:17:06

标签: python csv

我的代码用于打印pcap文件的输出IP的CSV文件工作正常,但问题是它只存储pcap文件的第一个数据包。我没有得到实际问题在哪里.. 有人可以帮我解决这个问题。

这是我的代码:

import dpkt
from dpkt.ip import IP
from dpkt.ethernet import Ethernet
import struct
import socket
import csv

def ip_to_str(address):
    return socket.inet_ntoa(address)

f = open('sample.pcap', 'rb')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    if eth.type != dpkt.ethernet.ETH_TYPE_IP:
        continue

    ip = eth.data
    do_not_fragment = bool(dpkt.ip.IP_DF)
    more_fragments = bool(dpkt.ip.IP_MF)
    fragment_offset = bool(dpkt.ip.IP_OFFMASK)
    c = csv.writer(open("a.csv", "wb"))

    Source = "%s" % ip_to_str(ip.src)
    Destination = "%s" % ip_to_str(ip.dst)
    Length = "%d" % (ip.len)
    TTL = "%d" % (ip.ttl)
    OFF = ip.off
    TOS = ip.tos
    Protocol = ip.p
    data = (Source, Destination, Length, TTL, TOS, OFF, Protocol)
    c.writerow(data)

2 个答案:

答案 0 :(得分:0)

您的代码当前正在循环中打开一个csv文件,因此每次创建新版本的“a.csv”并且只向其写入一个数据包。将文件创建语句移到循环之外,并继续在循环内写入。

import dpkt
from dpkt.ip import IP
from dpkt.ethernet import Ethernet
import struct
import socket
import csv

def ip_to_str(address):
    return socket.inet_ntoa(address)

f = open('sample.pcap', 'rb')
pcap = dpkt.pcap.Reader(f)
c = csv.writer(open("a.csv", "wb"))  # <=== moved here
for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    if eth.type != dpkt.ethernet.ETH_TYPE_IP:
        continue

    ip = eth.data
    do_not_fragment = bool(dpkt.ip.IP_DF)
    more_fragments = bool(dpkt.ip.IP_MF)
    fragment_offset = bool(dpkt.ip.IP_OFFMASK)

    Source = "%s" % ip_to_str(ip.src)
    Destination = "%s" % ip_to_str(ip.dst)
    Length = "%d" % (ip.len)
    TTL = "%d" % (ip.ttl)
    OFF = ip.off
    TOS = ip.tos
    Protocol = ip.p
    data = (Source, Destination, Length, TTL, TOS, OFF, Protocol)
    c.writerow(data)

答案 1 :(得分:0)

您需要确保在循环结束时关闭文件;并且正如提到的那样正确地缩进你的代码:

import struct
import socket
import csv

import dpkt

from dpkt.ip import IP
from dpkt.ethernet import Ethernet

def ip_to_str(address):
    return socket.inet_ntoa(address)

with open('sample.pcap', 'rb') as f:
    pcap = dpkt.pcap.Reader(f)

results = []
for ts, buf in pcap:
    eth = dpkt.ethernet.Ethernet(buf)
    if eth.type != dpkt.ethernet.ETH_TYPE_IP:
        continue

    ip = eth.data
    do_not_fragment = bool(dpkt.ip.IP_DF)
    more_fragments = bool(dpkt.ip.IP_MF)
    fragment_offset = bool(dpkt.ip.IP_OFFMASK)

    data = [ip_to_str(ip.src),
            ip_to_str(ip.dst),
            ip.len,
            ip.ttl,
            ip.off,
            ip.tos,
            ip.p]
    results.append(data)

with open('output.csv', 'wb') as f:
    writer = csv.writer(f, delimiter=',', quotechar='"')
    writer.writerows(results)