Get info line from scapy package

I am using scapy 2.3.1-dev not interactively (i.e. as a library) in the tool that I am creating. I would like to get a line of readable package information, for example, you get from scapy.all.Packet.show(). I tried to use all three methods ( packet.show(), packet.show2()and packet.display()) that provide information, but none of them returns anything, instead they print out the information I need.

In addition, the information returned packet.__repr__()is not enough.

Are there any functions / methods that return well-formatted text in the same way as, for example, packet.show()prints them? If there is no way to capture / intercept the output show()before it is printed to the console?

I know that I can do my own string formatting using the information from packet.fields, but I try not to.

+4
source share
2 answers

One possible way is to redirect the output of the function packet.show()to a variable capture. The following example shows an example:

import sys
from StringIO import StringIO
from scapy.layers import inet
from scapy.all import *

#Create scapy packet
pack=inet.Ether()/inet.IP()/inet.TCP()

#Redirect output of print to variable 'capture'
capture = StringIO()
save_stdout = sys.stdout
sys.stdout = capture
pack.show()
sys.stdout = save_stdout

#capture.getvalue() is a string with the output of 'pack.show()' 
print capture.getvalue()

#Verify that capture.getvalue() is a string
print isinstance(capture.getvalue(), basestring)

Program Output:

###[ Ethernet ]###
  dst       = ff:ff:ff:ff:ff:ff
  src       = 00:00:00:00:00:00
  type      = 0x800
###[ IP ]###
     version   = 4
     ihl       = None
     tos       = 0x0
     len       = None
     id        = 1
     flags     = 
     frag      = 0
     ttl       = 64
     proto     = tcp
     chksum    = None
     src       = 127.0.0.1
     dst       = 127.0.0.1
     \options   \
###[ TCP ]###
        sport     = ftp_data
        dport     = http
        seq       = 0
        ack       = 0
        dataofs   = None
        reserved  = 0
        flags     = S
        window    = 8192
        chksum    = None
        urgptr    = 0
        options   = {}

True
+5
source

You can use the show()method show(dump=True), then it will return a string to you. Why do I know this because I read the method code show().

here is the code:

def main():
    packet = scapy.rdpcap('1.pcap')
    for p in packet:
        a = p.show(dump=True)
        print type(a)
        print a
        exit(0)
-1
source

All Articles