英文:
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论