Search code examples
pythonstringpacketscapy

Putting Packet.show() representation in string variable


Is it somehow possible to put the representation which Packet.show() gives me into a string variable?

Like this

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

So I can store it for later use and print it when needed?


Solution

  • .show() just print to stdout. You need to replace sys.stdout with an object that can hold written strings.

    For example, in the following example, io.BytesIO is used to capture the written string:

    >>> 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'