[Python] Read Scapy (/Python) source code from file and execute

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    For a testing application, I've created a test file with the following contents:

    packets.scapy:

    Ether() / IP(dst='1.1.1.1') / Raw(load='foobar')
    Ether() / IP(dst='1.1.1.2') / Raw(load='foobar')
    Ether() / IP(dst='1.1.1.3') / Raw(load='foobar')


    I can read this file and create an instance of each line using eval() as such:

    from scapy.all import *

    with open('packets.scapy') as f:
    data = f.read()

    objects = []
    for line in data.splitlines():
    objects.append(eval(line)())


    But I like to extend the functionality with variables and formatting:

    packets_formatted.scapy:

    payload = 'foobar'

    (Ether()
    / IP(dst='1.1.1.1')
    / Raw(load=payload)
    )

    (Ether()
    / IP(dst='1.1.1.2')
    / Raw(load=payload)
    )

    (Ether()
    / IP(dst='1.1.1.3')
    / Raw(load=payload)
    )


    Now eval() does not work anymore. How can I instantiate each object, and evaluate the payload variable?

    I experimented a bit with the compile() function:

    with open('packets_formatted.scapy', 'rb') as f:
    data = f.read()

    code = compile(data, 'packets_formatted.scapy', 'exec')


    But I did not find out how to use the code object to create objects and put them in a list.

    Edit:

    I found that this actually works:

    packets_formatted.scapy:

    payload = 'foobar'

    packets = []

    packets.append(Ether()
    / IP(dst='1.1.1.1')
    / Raw(load=payload)
    )

    packets.append(Ether()
    / IP(dst='1.1.1.2')
    / Raw(load=payload)
    )

    packets.append(Ether()
    / IP(dst='1.1.1.3')
    / Raw(load=payload)
    )


    exec(open('packets_formatted.scapy').read())

    This is a workable solution for me, however now the file contains more detail then I'd like.

    I'm starting to realise that maybe I'm doing something very unusual.

    Continue reading...

Compartilhe esta Página