Get info string from scapy packet

感情迁移 提交于 2019-12-01 07:33:23

One of the possible ways is to redirect output of the packet.show() function to the variable capture. The following code provides 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)

Output of the program is:

###[ 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
MrMeizhi

You can use show() method by show(dump=True),then it will return string to you. Why Do I Know that,cause I read the code of show() method.

here is code:

def main():
    packet = scapy.rdpcap('1.pcap')
    for p in packet:
        a = p.show(dump=True)
        print type(a)
        print a
        exit(0)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!