我用于打印 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/