使用Python 3中的Scapy如何将PCAP写入字节或字符串?

huangapple go评论67阅读模式
英文:

How to use Scapy in Python 3 to write a PCAP to a byte or string?

问题

以下是代码部分的翻译:

我正在尝试将一个PCAP文件存储到一个字节变量中但我不知道如何做到这一点到目前为止我有以下代码

import io
from scapy.all import *

packet = Ether() / IP(dst="1.2.3.4") / UDP(dport=123)
packet = IP(src='127.0.0.1', dst='127.0.0.2')/TCP()/ "GET / HTTP/1.0\r\n\r\n"

content = b''
wrpcap(io.BytesIO(content), [packet])

但是 `content` 是空的我该如何使其工作
英文:

I am trying to get a PCAP into a byte variable, but I cannot figure out how to do it. So far I have something like:

import io
from scapy.all import *

packet = Ether() / IP(dst="1.2.3.4") / UDP(dport=123)
packet = IP(src='127.0.0.1', dst='127.0.0.2')/TCP()/"GET / HTTP/1.0\r\n\r\n"

content = b''
wrpcap(io.BytesIO(content), [packet])

But content is empty. How can I get this to work?

答案1

得分: 1

你在使用 BytesIO 时存在错误。content 不是流写入后的内容,而是流的初始值。

另外,wrpcap 在写入后会关闭文件(或类似文件的对象),因此无法再检索写入到 BytesIO 对象的数据。你可以使用答案中提到的方法绕过这个问题,具体可以参考此问题的答案

import contextlib

@contextlib.contextmanager
def uncloseable(fd):
    """
    在上下文的持续时间内,将fd的关闭操作变为无操作的上下文管理器。
    """
    close = fd.close
    fd.close = lambda: None
    yield fd
    fd.close = close

content = io.BytesIO()
with uncloseable(content):
    wrpcap(content, [packet])

content.seek(0)
print(content.read())
英文:

You're using BytesIO incorrectly. content is not the contents of the stream after it's been written to, it's the initial value of the stream.

Additionally wrpcap closes the file (or file-like object) after writing to it so you can no longer retrieve the data written to the BytesIO object. You can get around this with a hack suggested in the answer to this question.

import contextlib

@contextlib.contextmanager
def uncloseable(fd):
    """
    Context manager which turns the fd's close operation to no-op for the duration of the context.
    """
    close = fd.close
    fd.close = lambda: None
    yield fd
    fd.close = close

content = io.BytesIO()
with uncloseable(content):
    wrpcap(content, [packet])

content.seek(0)
print(content.read())

huangapple
  • 本文由 发表于 2023年2月24日 06:28:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定