用scapy将pcap写入Buffer

时间:2016-10-22 23:21:14

标签: python buffer scapy pcap bytesio

我在将pcap写入文件缓冲区时遇到问题,重要的是我没有触摸这些pcap捕获的磁盘,是的,它们必须是活的。

sudo scapy
>>> import io
>>> cap = sniff(timeout=30)
>>> buf = io.BytesIO()
>>> wrpcap(buf, cap)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/scapy/utils.py", line 524, in wrpcap
    with PcapWriter(filename, *args, **kargs) as fdesc:
  File "/usr/lib/python2.7/dist-packages/scapy/utils.py", line 682, in __init__
    self.f = [open,gzip.open][gz](filename,append and "ab" or "wb", gz and 9 or bufsz)
TypeError: coercing to Unicode: need string or buffer, _io.BytesIO found

这通常发生在您打开(无)时,这是Scapy Utils中PcapWriter函数中的错误吗?

我在编写之前还尝试过:buf.seek(0),但仍然失败。

2 个答案:

答案 0 :(得分:1)

你应该使用Scapy的最新版本,它开箱即用:

Welcome to Scapy (2.3.3)
>>> import io
>>> cap = sniff(timeout=30)
>>> buf = io.BytesIO()
>>> wrpcap(buf, cap)
>>>

如果您需要保持buf打开,请执行以下操作:

Welcome to Scapy (2.3.3)
>>> import io
>>> cap = sniff(timeout=30)
>>> buf = io.BytesIO()
>>> PcapWriter(buf).write(cap)
>>> buf.seek(0)
0L
>>> rdpcap(buf)
<No name: TCP:736 UDP:0 ICMP:0 Other:0>

答案 1 :(得分:-1)

我从scapyutils.py)获取了代码并创建了memwrpcap,可以写入io.BytesIO

buf = io.BytesIO()
memwrpcap(buf, cap)

(写完之后它不会关闭缓冲区,你可以开始从缓冲区开始读取。)

之后我使用标准open()write()来保存io.BytesIO的数据,并将此文件与使用wrpcap

创建的文件进行比较
diff -c test-std.pcap test-mem.pcap

似乎它们是相同的,因此io.BytesIO包含pcap格式的数据。

完整代码 - memwrpcamMemoryPcapWriter以及我用来测试它的代码。

#
# from: scapy/utils.py
#

from scapy.all import *

def memwrpcap(filename, pkt, *args, **kargs):
    """Write a list of packets to a pcap file
    gz: set to 1 to save a gzipped capture
    linktype: force linktype value
    endianness: "<" or ">", force endianness"""

    # use MemoryPcapWriter instead of PcapWriter
    with MemoryPcapWriter(filename, *args, **kargs) as fdesc:
        fdesc.write(pkt)


class MemoryPcapWriter(PcapWriter):
    """A stream PCAP writer with more control than wrpcap()"""
    def __init__(self, filename, linktype=None, gz=False, endianness="", append=False, sync=False):
        """
        linktype: force linktype to a given value. If None, linktype is taken
                  from the first writter packet
        gz: compress the capture on the fly
        endianness: force an endianness (little:"<", big:">"). Default is native
        append: append packets to the capture file instead of truncating it
        sync: do not bufferize writes to the capture file
        """

        self.linktype = linktype
        self.header_present = 0
        self.append=append
        self.gz = gz
        self.endian = endianness
        self.filename=filename
        self.sync=sync
        bufsz=4096
        if sync:
            bufsz=0

        # use filename or file-like object 
        if isinstance(self.filename, str):
            self.f = [open,gzip.open][gz](filename,append and "ab" or "wb", gz and 9 or bufsz)
        else: # file-like object 
            self.f = filename

    def __exit__(self, exc_type, exc_value, tracback):
        self.flush()
        if isinstance(self.filename, str):
            self.close() # don't close file-like object


# --- main ---

#
# run script with sudo
#
# compare results (on Linux)
#    diff -s test-std.pcap test-mem.pcap
#

from scapy.all import *

import io

cap = sniff(timeout=5)

# save to pcap file
wrpcap('test-std.pcap', cap)

# save to buffer
buf = io.BytesIO()
memwrpcap(buf, cap)

# move to beginning and save to file
#print('current position:', buf.tell())
buf.seek(0)
#print('current position:', buf.tell())

with open('test-mem.pcap', 'wb') as fp:
    fp.write(buf.read())