将 Packet.show() 表示形式放入字符串变量中

Putting Packet.show() representation in string variable

是否可以将 Packet.show() 给我的表示放入字符串变量中?

像这样

representation = somePacket.show()
print representation # will print nothing

所以我可以存储它以备后用,并在需要时打印出来?

.show() 只是打印到标准输出。您需要将 sys.stdout 替换为可以保存写入字符串的对象。

例如下面的例子,使用io.BytesIO来抓取写入的字符串:

>>> import sys
>>> from io import BytesIO
>>> from scapy.all import Ether, IP, ICMP, Net
>>> packets = Ether()/IP(dst=Net("google.com/30"))/ICMP() 
>>> old_stdout, sys.stdout = sys.stdout, BytesIO()
>>> try:
...     packets.show()
...     output = sys.stdout.getvalue()  # retrieve written string
... finally:
...     sys.stdout = old_stdout  # Restore sys.stdout
... 
>>> output[:10]
'###[ Ether'