使用Python创建pcap文件

3

我正在尝试创建一个非常简单的PCAP文件(1个UDP消息)。
尝试使用dpkt(pcap.Writer),但没有成功,而且文档很少。
有人可以发布一个有效的示例吗?
(或其他任何替代方案-我不受dpkt的限制)

4个回答

14

2

0

construct's cap (链接失效) 展示了如何使用 construct。Construct 还有一个基本的 ip stack (链接失效) 示例。Construct 的好处在于它是对称的,即您可以将数据放入其中,将其转换为一组 Python 对象,然后可以转储对象以创建原始数据块。


我不理解...我需要创建一个pcap文件,但不确定它如何帮助我。 - Boaz
相当过时了.. 所有链接似乎都已失效 - Cukic0d

0
你可以尝试下面的代码:
#!/usr/bin/env python3
import sys
import struct
import os
import argparse

from scapy.all import sniff, sendp, hexdump, linehexdump, get_if_list, get_if_hwaddr
from scapy.all import Packet, IPOption
from scapy.all import ShortField, IntField, LongField, BitField, FieldListField, FieldLenField
from scapy.all import IP, TCP, UDP, Raw
from scapy.layers.inet import _IPOption_HDR
from scapy.all import raw
from scapy.all import bytes_hex
import hashlib
import pcapng.blocks as blocks
from pcapng import FileWriter


counter = 1

def get_if():
    ifs=get_if_list()
    iface=None
    for i in get_if_list():
        if "enp1s0f1" in i:
            iface=i
            break;
    if not iface:
        print("Cannot find eth0 interface")
        exit(1)
    return iface


def main():
    global counter
    ifaces = [i for i in os.listdir('/sys/class/net/') ]
    iface = get_if()
    print(("sniffing on %s" % iface))
    sys.stdout.flush()
    writer = FileWriter(args.outfile, shb)

    orig_packets = sniff(filter='tcp and port 5201',iface = iface)
    for packet in orig_packets:
        spb = shb.new_member(blocks.SimplePacket)
        spb.packet_data = bytes(packet)
        writer.write_block(spb)
        print("C=",counter)
        counter=counter+1

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("outfile", type=argparse.FileType("wb"))
    args = parser.parse_args()

    shb = blocks.SectionHeader(
    options={
        "shb_hardware": "artificial",
        "shb_os": "python",
        "shb_userappl": "python-pcapng",
    })
    idb = shb.new_member(
    blocks.InterfaceDescription,
    link_type=1,
    options={
        "if_description": "Hand-rolled",
        "if_os": "Python",
        "if_filter": [(0, b"tcp port 5201 and host 192.168.1.3")],
    },)

    main()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接