简体   繁体   中英

Get second layer from PCAP with Python/Scapy

I'm trying to read and enumerate a pcap file from Python but when doing so I only seem to be getting the layer 3 data even when the layer 2 data is present:

Here's my code:

import pprint
from scapy.all import *

target_cap = 'hello.pcap'

parser = PcapReader(root_dir + target_cap)

for i,p in enumerate(parser):
    pkt = p.payload
    pprint.pprint(pkt)

IE output:

<IP  version=4L ihl=5L tos=0x0 len=52 id=12220 flags=DF frag=0L ttl=128 proto=tcp chksum=0x453a src=192.168.2.100 dst=192.168.2.25 options=[] |<TCP  sport=sddp dport=mbap seq=1584390497 ack=1497344211 dataofs=5L reserved=0L flags=PA window=65325 chksum=0xe356 urgptr=0 options=[] |<Raw  load='\x00\x00\x00\x00\x00\x06\xff\x01\x00\x00\x00\x01' |>>>
<IP  version=4L ihl=5L tos=0x0 len=50 id=30949 flags= frag=0L ttl=64 proto=tcp chksum=0x7c13 src=192.168.2.25 dst=192.168.2.100 options=[] |<TCP  sport=mbap dport=sddp seq=1497344211 ack=1584390509 dataofs=5L reserved=0L flags=PA window=4096 chksum=0xd17d urgptr=0 options=[] |<Raw  load='\x00\x00\x00\x00\x00\x04\xff\x01\x01\x00' |>>>
<IP  version=4L ihl=5L tos=0x0 len=40 id=12226 flags=DF frag=0L ttl=128 proto=tcp chksum=0x4540 src=192.168.2.100 dst=192.168.2.25 options=[] |<TCP  sport=sddp dport=mbap seq=1584390509 ack=1497344221 dataofs=5L reserved=0L flags=A window=65315 chksum=0xe267 urgptr=0 |>>
<IP  version=4L ihl=5L tos=0x0 len=52 id=12240 flags=DF frag=0L ttl=128 proto=tcp chksum=0x4526 src=192.168.2.100 dst=192.168.2.25 options=[] |<TCP  sport=sddp dport=mbap seq=1584390509 ack=1497344221 dataofs=5L reserved=0L flags=PA window=65315 chksum=0xe34a urgptr=0 options=[] |<Raw  load='\x00\x00\x00\x00\x00\x06\xff\x01\x00\x00\x00\x01' |>>>
<IP  version=4L ihl=5L tos=0x0 len=40 id=30972 flags= frag=0L ttl=64 proto=tcp chksum=0x7c06 src=192.168.2.25 dst=192.168.2.100 options=[] |<TCP  sport=mbap dport=sddp seq=1497344221 ack=1584390521 dataofs=5L reserved=0L flags=A window=4096 chksum=0xd17f urgptr=0 |<Padding  load='\x00\x00\x00\x00\x00\x00' |>>>

In this case I'm only interested in the layer 2 metadata, how can I fetch that instead?

Your code intentionally prints just the payload of the packet, and not the headers. This means that you print the N+1st layers each time.

Also, and unrelated to your problem, you don't need enumerate in your sample program.

Try this instead:

for p in parser:
    pprint.pprint(p)

If you want to examine the packet data instead of merely printing it, that's easy, too:

# Sample code to print IP/MAC relationships:
for p in parser:
    if Ether in p and IP in p:
        print p[Ether].dst, p[IP].dst
        print p[Ether].src, p[IP].src

Reference: http://www.secdev.org/projects/scapy/doc/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM