从 scapy 数据包中获取信息字符串 [英] Get info string from scapy packet
问题描述
我正在构建的工具中以非交互方式(即作为库)使用 scapy 2.3.1-dev.我想获取有关数据包的一串人类可读信息,例如您从 scapy.all.Packet.show()
获取的信息.我已经尝试使用所有三种方法(packet.show()
、packet.show2()
和 packet.display()
)提供信息,但这些都没有返回任何内容,而是打印出我想要的信息.
I am using scapy 2.3.1-dev non-interactively (i.e. as a library) in a tool I am building. I would like to get a string of human-readable information about a packet, such as you get from scapy.all.Packet.show()
. I have tried using all three of the methods (packet.show()
, packet.show2()
and packet.display()
) that provide the info, but none of these return anything, instead they print out the information that I want.
另外,packet.__repr__()
返回的信息还不够.
Also, the information returned by packet.__repr__()
is not quite enough.
是否有任何函数/方法可以以相同的方式返回格式良好的文本,例如packet.show()
打印它们?如果没有,是否有某种方法可以在 show()
的输出被打印到控制台之前捕获/拦截它?
Are there any functions/methods that would return the nicely-formatted text the same way that e.g. packet.show()
prints them? If not is there some way of capturing/intercepting the output of show()
, before it gets printed to the console?
我知道我可以使用 packet.fields
中的信息进行我自己的字符串格式化,但我试图避免这样做.
I am aware that I can do my own string formatting, using the info from packet.fields
, but I am trying to avoid having to do that.
推荐答案
一种可能的方法是将 packet.show()
函数的输出重定向到变量 capture代码>.以下代码提供了一个示例:
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)
程序的输出为:
###[ 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
这篇关于从 scapy 数据包中获取信息字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!