Converting a sniffed scapy packet to bytes

与世无争的帅哥 提交于 2020-01-06 02:54:11

问题


When sniffing packets with scapy I can save them to a variable

sniffed = sniff(count=1)

Now I would like to see what's inside the packet by doing

print sniffed

or

print str(sniffed)

but all this gives me is something like the following:

������0�    E4h@@����������� l��

which isn't quite what I need. So how can I convert a sniffed packet into human readable Binary, or an array of Bytes or something more useful so that I can see what's inside? I have already tried using struct.unpack(format, packet) with formats like "!B", but that does not seem to be the right solution, because the packet can be longer than one Byte or a Short or an Int.


Example for what I'm trying

>>> packet = sniff(count=1)[0]
>>> hexdump(packet)
0000   00 50 56 8E 00 0D 14 CC  20 16 E7 59 08 00 45 00   .PV..... ..Y..E.
0010   00 34 6B AB 40 00 40 06  C6 48 AC 11 8A E2 68 10   .4k.@.@..H....h.
0020   69 CC B5 47 00 50 E9 85  17 B0 BA EF 29 B2 80 10   i..G.P......)...
0030   01 DD 8D 58 00 00 01 01  08 0A 00 0E A2 C0 03 5D   ...X...........]
0040   9D 1C 
>>> packetByteArray = bytearray(repr(str(packet)))
>>> hex(packetByteArray[0])
'0x27'
>>>

But in the hexdump I can see that the first Byte is actually 0x00 and not 0x27


回答1:


You are probably searching for scapy Hexdump(pkt) or hexraw(pkt) or repr(str(pkt)) for string encoded output. Note that sniff returns a list, not a single pkt.

If you want to access serialized packet bytes one by one just serialize the layers str(pkt) to get a python (char/byte)-string.

for b in str(pkt):
    print "char: %s ord/value: %d hex: %x"%(b,ord(b),ord(b))



回答2:


If you have already read the packet as pkt you may see bytes by time :

pktBytes=[]
pktTimes=[]
from datetime import datetime
#Read each packet and append to the lists.
for p in pkt:
    if IP in p:
        try:
            pktBytes.append(p[IP].len)
            pktTime=datetime.fromtimestamp(p.time)
            pktTimes.append(pktTime.strftime("%Y-%m-%d %H:%M:%S.%f"))
        except:
            pass

# Convert list to series
bytes = pd.Series(pktBytes).astype(int)

# Convert the timestamp list to a pd date_time with the option “errors=coerce” to handle errors.
times = pd.to_datetime(pd.Series(pktTimes).astype(str),  errors='coerce')

# Build the dataframe, set time as index
df  = pd.DataFrame({'Bytes': bytes, 'Times':times})
df = df.set_index('Times')

# See how it looks in 2 seconds sums
df.resample('2S').sum().plot()


来源:https://stackoverflow.com/questions/34791583/converting-a-sniffed-scapy-packet-to-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!