簡體   English   中英

在csv文件python中打印輸出

[英]print output in csv file python

我用於打印pcap文件IP的IN CSV FILE輸出的代碼運行良好,但問題是它只存儲了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)

您需要確保在循環結束時關閉文件; 並且正如提到的那樣正確縮進代碼:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM