python - 在csv文件python中打印输出

标签 python csv

我用于打印 pcap 文件 IP 的 IN 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)

最佳答案

您的代码当前正在循环内打开一个 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)

关于python - 在csv文件python中打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35285168/

相关文章:

python - 图形工具:通过用户定义的标签查找顶点

vba - 使用 TextFileColumnDataTypes 打开每列具有正确数据格式的 CSV 文件?

python - 如何在 python 中使用 pandas 读取 csv 文件的所有行?

c - 从文件读取数据后动态存储数据

python - 是否有与 Ruby 的 officer gem 等效的 Python?

python - 如何在 Python 中计算字符串的数字、字母、空格?

python - 如何在圆形分布中生成随机点

xml - 在 Go 中将通用 csv 转换为 xml

java - 如何用Java仅将csv文件上传到服务器

python - 在运行时在 Django 中指定关系动词?