简体   繁体   English

Scapy:如何在现有数据包中插入新层(802.1q)?

[英]Scapy: How to insert a new layer (802.1q) into existing packet?

I have a packet dump and want to inject a vlan tag (802.1q header) to the packets. 我有一个数据包转储,并希望向数据包注入vlan标记(802.1q标头)。
How to do that? 怎么做?

To find the answer, I had a look at Scapy: Inserting a new layer and logging issues , which is really helpful, but contains some cruft. 为了找到答案,我看了一下Scapy:插入一个新图层和记录问题 ,这确实很有用,但包含了一些内容。

My solution for adding a layer, based on the referenced question (add-dot1q_pcap.py): 我根据引用的问题(add-dot1q_pcap.py)添加图层的解决方案:

import sys
from scapy.all import rdpcap, wrpcap, NoPayload, Ether, Dot1Q

# read all packets into buffer
# WARNING works only for small files
packets = []

for packet in rdpcap(sys.argv[1]):
    # gets the first layer of the current packet
    layer = packet.firstlayer()
    # loop over the layers
    while not isinstance(layer, NoPayload):
        if 'chksum' in layer.default_fields:
            del layer.chksum

        if (type(layer) is Ether):
            # adjust ether type
            layer.type = 33024
            # add 802.1q layer between Ether and IP
            dot1q = Dot1Q(vlan=42)
            dot1q.add_payload(layer.payload)
            layer.remove_payload()
            layer.add_payload(dot1q)
            layer = dot1q

        # advance to the next layer
        layer = layer.payload
    packets.append(packet)

wrpcap(sys.argv[2], packets)

The script adds a vlan tag with vlan id 42. 该脚本添加了vlan id为42的vlan标记。

Usage: ./add-dot1q_pcap.py <source_file> <output_file> 用法: ./add-dot1q_pcap.py <source_file> <output_file>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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