snappi-trex is a snappi plugin that allows executing scripts written using snappi with Cisco's TRex Traffic Generator

Related tags

Networkingsnappi-trex
Overview

snappi-trex

license Project Status: Active – The project has reached a stable, usable state and is being actively developed. Build Total alerts Language grade: Python pypi python

snappi-trex is a snappi plugin that allows executing scripts written using snappi with Cisco's TRex Traffic Generator

Design

snappi-trex converts snappi Open Traffic Generator API configuration into the equivalent TRex STL Client configuration. This allows users to use the TRex Traffic Generator and its useful features without having to write complex TRex scripts.

diagram

The above diagram outlines the overall process of how the snappi Open Traffic Generator API is able to interface with TRex and generate traffic over its network interfaces. snappi-trex is essential to convert snappi scripts into the equivalent TRex STL Client instructions.


snappi-trex usage follows the standard usage of snappi with a few modifications outlined in the Usage document.

Demos

Click here for the Quickstart Guide Video Tutorial

  • This goes over the installation and setup for snappi-trex, and how to run a basic snappi script using snappi-trex

Click here for the snappi-trex P4 PTF Demo

  • This demonstrates snappi-trex being used with the P4 Packet Testing Framework in a 4 Port Mesh configuration

Table of Contents


Quickstart

snappi-trex is a snappi plugin that allows executing scripts written using snappi with Cisco's TRex Traffic Generator


--> Click here for the Quickstart Guide Video Tutorial


Installing and Running TRex

TRex must be installed and running before proceeding

TRex must be installed and configured in order to use snappi-trex. For a quick tutorial on TRex installation, running, and basic usage, check out my TRex Tutorial


Installing snappi-trex

Make sure python-pip3 is installed

sudo apt-get install python3-pip

Install snappi and the snappi-trex extension

pip3 install snappi==0.4.26 snappi[trex]

Start Scripting

Let's run our first script called hello_snappi_trex.py: A basic snappi script that transmits 1000 UDP packets bidirectionally between two ports and verifies that they are received. This file can be found at examples/hello_snappi_trex.py in the snappi-trex Github Repo.

git clone https://github.com/open-traffic-generator/snappi-trex
python3 snappi-trex/examples/hello_snappi_trex.py

You may also just paste the script in from below.

hello_snappi_trex.py
p2').flow(name='flow p2->p1') # and assign source and destination ports for each f1.tx_rx.port.tx_name, f1.tx_rx.port.rx_name = p1.name, p2.name f2.tx_rx.port.tx_name, f2.tx_rx.port.rx_name = p2.name, p1.name # configure packet size, rate and duration for both flows f1.size.fixed, f2.size.fixed = 128, 256 for f in cfg.flows: # send 1000 packets and stop f.duration.fixed_packets.packets = 1000 # send 1000 packets per second f.rate.pps = 1000 # configure packet with Ethernet, IPv4 and UDP headers for both flows eth1, ip1, udp1 = f1.packet.ethernet().ipv4().udp() eth2, ip2, udp2 = f2.packet.ethernet().ipv4().udp() # set source and destination MAC addresses eth1.src.value, eth1.dst.value = '00:AA:00:00:04:00', '00:AA:00:00:00:AA' eth2.src.value, eth2.dst.value = '00:AA:00:00:00:AA', '00:AA:00:00:04:00' # set source and destination IPv4 addresses ip1.src.value, ip1.dst.value = '10.0.0.1', '10.0.0.2' ip2.src.value, ip2.dst.value = '10.0.0.2', '10.0.0.1' # set incrementing port numbers as source UDP ports udp1.src_port.increment.start = 5000 udp1.src_port.increment.step = 2 udp1.src_port.increment.count = 10 udp2.src_port.increment.start = 6000 udp2.src_port.increment.step = 4 udp2.src_port.increment.count = 10 # assign list of port numbers as destination UDP ports udp1.dst_port.values = [4000, 4044, 4060, 4074] udp2.dst_port.values = [8000, 8044, 8060, 8074, 8082, 8084] print('Pushing traffic configuration ...') api.set_config(cfg) print('Starting packet capture on all configured ports ...') cs = api.capture_state() cs.state = cs.START api.set_capture_state(cs) print('Starting transmit on all configured flows ...') ts = api.transmit_state() ts.state = ts.START api.set_transmit_state(ts) print('Checking metrics on all configured ports ...') print('Expected\tTotal Tx\tTotal Rx') assert wait_for(lambda: metrics_ok(api, cfg)), 'Metrics validation failed!' assert captures_ok(api, cfg), 'Capture validation failed!' print('Test passed !') def metrics_ok(api, cfg): # create a port metrics request and filter based on port names req = api.metrics_request() req.port.port_names = [p.name for p in cfg.ports] # include only sent and received packet counts req.port.column_names = [req.port.FRAMES_TX, req.port.FRAMES_RX] # fetch port metrics res = api.get_metrics(req) # calculate total frames sent and received across all configured ports total_tx = sum([m.frames_tx for m in res.port_metrics]) total_rx = sum([m.frames_rx for m in res.port_metrics]) expected = sum([f.duration.fixed_packets.packets for f in cfg.flows]) print('%d\t\t%d\t\t%d' % (expected, total_tx, total_rx)) return expected == total_tx and total_rx >= expected def captures_ok(api, cfg): import dpkt print('Checking captured packets on all configured ports ...') print('Port Name\tExpected\tUDP packets') result = [] for p in cfg.ports: exp, act = 1000, 0 # create capture request and filter based on port name req = api.capture_request() req.port_name = p.name # fetch captured pcap bytes and feed it to pcap parser dpkt pcap = dpkt.pcap.Reader(api.get_capture(req)) for _, buf in pcap: # check if current packet is a valid UDP packet eth = dpkt.ethernet.Ethernet(buf) if isinstance(eth.data.data, dpkt.udp.UDP): act += 1 print('%s\t\t%d\t\t%d' % (p.name, exp, act)) result.append(exp == act) return all(result) def wait_for(func, timeout=10, interval=0.2): """ Keeps calling the `func` until it returns true or `timeout` occurs every `interval` seconds. """ import time start = time.time() while time.time() - start <= timeout: if func(): return True time.sleep(interval) print('Timeout occurred !') return False if __name__ == '__main__': hello_snappi_trex() ">
import snappi
import sys, os

# Replace v2.90 with the installed version of TRex. 
# Change '/opt/trex' if you installed TRex in another location
trex_path = '/opt/trex/v2.90/automation/trex_control_plane/interactive'
sys.path.insert(0, os.path.abspath(trex_path))


def hello_snappi_trex():
    """
    This script does following:
    - Send 1000 packets back and forth between the two ports at a rate of
      1000 packets per second.
    - Validate that total packets sent and received on both interfaces is as
      expected using port metrics.
    - Validate that captured UDP packets on both the ports are as expected.
    """
    # create a new API instance where host points to controller
    api = snappi.api(ext='trex')
    # and an empty traffic configuration to be pushed to controller later on
    cfg = api.config()

    # add two ports where location points to traffic-engine (aka ports)
    p1, p2 = (
        cfg.ports
        .port(name='p1')
        .port(name='p2')
    )

    # add layer 1 property to configure same speed on both ports
    ly = cfg.layer1.layer1(name='ly')[-1]
    ly.port_names = [p1.name, p2.name]
    ly.speed = ly.SPEED_1_GBPS

    # enable packet capture on both ports
    cp = cfg.captures.capture(name='cp')[-1]
    cp.port_names = [p1.name, p2.name]

    # add two traffic flows
    f1, f2 = cfg.flows.flow(name='flow p1->p2').flow(name='flow p2->p1')
    # and assign source and destination ports for each
    f1.tx_rx.port.tx_name, f1.tx_rx.port.rx_name = p1.name, p2.name
    f2.tx_rx.port.tx_name, f2.tx_rx.port.rx_name = p2.name, p1.name

    # configure packet size, rate and duration for both flows
    f1.size.fixed, f2.size.fixed = 128, 256
    for f in cfg.flows:
        # send 1000 packets and stop
        f.duration.fixed_packets.packets = 1000
        # send 1000 packets per second
        f.rate.pps = 1000

    # configure packet with Ethernet, IPv4 and UDP headers for both flows
    eth1, ip1, udp1 = f1.packet.ethernet().ipv4().udp()
    eth2, ip2, udp2 = f2.packet.ethernet().ipv4().udp()

    # set source and destination MAC addresses
    eth1.src.value, eth1.dst.value = '00:AA:00:00:04:00', '00:AA:00:00:00:AA'
    eth2.src.value, eth2.dst.value = '00:AA:00:00:00:AA', '00:AA:00:00:04:00'

    # set source and destination IPv4 addresses
    ip1.src.value, ip1.dst.value = '10.0.0.1', '10.0.0.2'
    ip2.src.value, ip2.dst.value = '10.0.0.2', '10.0.0.1'

    # set incrementing port numbers as source UDP ports
    udp1.src_port.increment.start = 5000
    udp1.src_port.increment.step = 2
    udp1.src_port.increment.count = 10

    udp2.src_port.increment.start = 6000
    udp2.src_port.increment.step = 4
    udp2.src_port.increment.count = 10

    # assign list of port numbers as destination UDP ports
    udp1.dst_port.values = [4000, 4044, 4060, 4074]
    udp2.dst_port.values = [8000, 8044, 8060, 8074, 8082, 8084]

    print('Pushing traffic configuration ...')
    api.set_config(cfg)

    print('Starting packet capture on all configured ports ...')
    cs = api.capture_state()
    cs.state = cs.START
    api.set_capture_state(cs)

    print('Starting transmit on all configured flows ...')
    ts = api.transmit_state()
    ts.state = ts.START
    api.set_transmit_state(ts)

    print('Checking metrics on all configured ports ...')
    print('Expected\tTotal Tx\tTotal Rx')
    assert wait_for(lambda: metrics_ok(api, cfg)), 'Metrics validation failed!'

    assert captures_ok(api, cfg), 'Capture validation failed!'

    print('Test passed !')


def metrics_ok(api, cfg):
    # create a port metrics request and filter based on port names
    req = api.metrics_request()
    req.port.port_names = [p.name for p in cfg.ports]
    # include only sent and received packet counts
    req.port.column_names = [req.port.FRAMES_TX, req.port.FRAMES_RX]

    # fetch port metrics
    res = api.get_metrics(req)
    # calculate total frames sent and received across all configured ports
    total_tx = sum([m.frames_tx for m in res.port_metrics])
    total_rx = sum([m.frames_rx for m in res.port_metrics])
    expected = sum([f.duration.fixed_packets.packets for f in cfg.flows])

    print('%d\t\t%d\t\t%d' % (expected, total_tx, total_rx))

    return expected == total_tx and total_rx >= expected


def captures_ok(api, cfg):
    import dpkt
    print('Checking captured packets on all configured ports ...')
    print('Port Name\tExpected\tUDP packets')

    result = []
    for p in cfg.ports:
        exp, act = 1000, 0
        # create capture request and filter based on port name
        req = api.capture_request()
        req.port_name = p.name
        # fetch captured pcap bytes and feed it to pcap parser dpkt
        pcap = dpkt.pcap.Reader(api.get_capture(req))
        for _, buf in pcap:
            # check if current packet is a valid UDP packet
            eth = dpkt.ethernet.Ethernet(buf)
            if isinstance(eth.data.data, dpkt.udp.UDP):
                act += 1

        print('%s\t\t%d\t\t%d' % (p.name, exp, act))
        result.append(exp == act)

    return all(result)


def wait_for(func, timeout=10, interval=0.2):
    """
    Keeps calling the `func` until it returns true or `timeout` occurs
    every `interval` seconds.
    """
    import time
    start = time.time()

    while time.time() - start <= timeout:
        if func():
            return True
        time.sleep(interval)

    print('Timeout occurred !')
    return False


if __name__ == '__main__':
    hello_snappi_trex()


Output

If everything is working correctly, you should see a similar output as this.

Pushing traffic configuration ...
Starting packet capture on all configured ports ...
Starting transmit on all configured flows ...
Checking metrics on all configured ports ...
Expected        Total Tx        Total Rx
2000            19              17
2000            445             437
2000            881             881
2000            1325            1325
2000            1761            1761
2000           2000            2000
Checking captured packets on all configured ports ...
Port Name       Expected        UDP packets
p1              1000            1000
p2              1000            1000
Test passed !
You might also like...
These scripts send notifications to a Webex space when a new IP is banned by Expressway, and allow to request more info or change the ban status
These scripts send notifications to a Webex space when a new IP is banned by Expressway, and allow to request more info or change the ban status

Spam Call and Toll Fraud Mitigation Cisco Expressway release X14 is able to mitigate spam calls and toll fraud attempts by jailing the spam IP address

A repository dedicated to IoT(internet of things ) and python scripts
A repository dedicated to IoT(internet of things ) and python scripts

📑 Introduction Week of Learning is a weekly program in which you will get all the necessary knowledge about Circuit-Building, Arduino and Micro-Contr

Repo used to maintain all notes and scripts developed during my DevNet Expert studies

DevNet Expert Studies Exam Date: TBD (Waiting for registration to open) This repository will be used to track my progress and maintain all notes/scrip

 Python Scripts for Cisco Identity Services Engine (ISE)
Python Scripts for Cisco Identity Services Engine (ISE)

A set of Python scripts to configure a freshly installed Cisco Identity Services Engine (ISE) for simple operation; in my case, a basic Cisco Software-Defined Access environment.

DataShare - Simple library for data sharing between scripts and public functions calling

DataShare - Simple library for data sharing between scripts and public functions calling. Installation. Install code, Delete LICENSE, README, readme.t

Python Scrcpy Client - allows you to view and control android device in realtime
Python Scrcpy Client - allows you to view and control android device in realtime

Python Scrcpy Client This package allows you to view and control android device in realtime. Note: This gif is compressed and experience lower quality

InfraGenie is allows you to split out your infrastructure project into separate independent pieces, each with its own terraform state.
InfraGenie is allows you to split out your infrastructure project into separate independent pieces, each with its own terraform state.

🧞 InfraGenie InfraGenie is allows you to split out your infrastructure project into separate independent pieces, each with its own terraform state. T

A simple and lightweight server that allows clients to connect and launch a shell remotely through a browser.

carrotsh A simple and lightweight server that allows clients to connect and launch a shell remotely through a browser. Uses xterm.js for the frontend

A web-based app that allows easy, simple - and if desired high-throughput - analysis of qPCR data
A web-based app that allows easy, simple - and if desired high-throughput - analysis of qPCR data

qpcr-Analyser A web-based GUI for the qpcr package that allows easy, simple and high-throughput analysis of qPCR data. As is described in more detail

Owner
Open Traffic Generator
Open Traffic Generator
Easy to use gRPC-web client in python

pyease-grpc Easy to use gRPC-web client in python Tutorial This package provides a requests like interface to make calls to gRPC-Web servers.

Sudipto Chandra 4 Dec 03, 2022
Dokumentasi belajar Network automation

Repositori belajar network automation dengan Docker, Python & GNS3 Using Frameworks and integrate with: Paramiko Netmiko Telnetlib CSV SFTP Netmiko, S

Daniel.Pepuho 3 Mar 15, 2022
ip2domain - get ip to domain, Know the domian corresponding to the local network connection IP

What is Sometimes, we need to know what connections our local machine has, and what are their IP, domain name, program and parameters? get ip to domai

51pwn 4 Sep 30, 2022
Huawei firewall automatically updates Chinese ip to target IP group.

Huawei firewall automatically updates Chinese ip to target IP group.

Lundaa 0 Jan 11, 2022
A simple framwork to streamline the Domain Adaptation training process.

FastDA Introduction This is a simple framework for domain adaptation training. You can use it to build your own training process. It heavily relies on

Vincent Zhang 7 Nov 22, 2022
A simple GitHub Action that physically puts your senses on alert when your build/release fails

GH Release Paniker A simple GitHub Action that physically puts your senses on alert when your build/release fails Usage Requirements: Raspberry Pi, LE

Hemanth Krishna 5 Dec 20, 2021
A network address manipulation library for Python

netaddr A system-independent network address manipulation library for Python 2.7 and 3.5+. (Python 2.7 and 3.5 support is deprecated). Provides suppor

711 Jan 05, 2023
Synchronised text editor over TCP, for live editing with others.

SyncTEd Synchronised text editor over TCP, for live editing with others. Written in Python with PyGame. Run Install requirements: pip install -r requi

Marko Živić 1 May 13, 2022
Arp Spoofer using Python 3.

ARP Spoofer / Wifi Killer By Auax Run: Run the application with the following command: python3 spoof.py -t target_ip_address -lh host_ip_address I

Auax 6 Sep 15, 2022
Interact remotely with the computer using Python and MQTT protocol 💻

Comandos_Remotos Interagir remotamento com o computador através do Python e protocolo MQTT. 💻 Status: em desenvolvimento 🚦 Objetivo: Interagir com o

Guilherme_Donizetti 6 May 10, 2022
A simple tool to utilize the basic functionality of the Private API From Virus Total

Welcome To VT-SCAN (viurs total api) Information This is a simple tool to utilize the basic functionality of the Private API From Virus Total. with th

0X0ŽĒR∅⁰ 1 Sep 21, 2022
CORS Bypass Proxy Cloud Function

CORS Bypass Proxy Cloud Function

Elayamani K 1 Oct 23, 2021
A Python Tor template on Gitpod

A Python Tor template on Gitpod This is template configured for ephemeral development environments on Gitpod. prebuild Get Started With Your Own Proje

Ivan Yastrebov 1 Dec 17, 2021
HTTP proxy pool server primarily meant for evading IP whitelists

proxy-forwarder HTTP proxy pool server primarily meant for evading IP whitelists. Setup Create a file named proxies.txt and fill it with your HTTP pro

h0nda 2 Feb 19, 2022
Modern Denial-of-service ToolKit for python

💣 Impulse Modern Denial-of-service ToolKit 💻 Main window 📡 Methods: Method Target Description SMS PHONE Sends a massive amount of SMS messages and

1 Nov 29, 2021
The AKS cluster provisioner provisions AKS clusters :-)

Overview The AKS cluster provisioner provisions AKS clusters :-) It uses the Azure CLI to configure VNet and subnets before creating the cluster itsel

Gigi Sayfan 1 Nov 10, 2021
Simple Port Scanner script written in Python, plans is to expand upon this script to turn it into a GUI based pen testing suite

PortScanner Simple Port Scanner script written in Python, plans is to expand upon this script to turn it into a GUI based pen testing suite. #IMPORTAN

1 Oct 23, 2021
Rufus is a Dos tool written in Python3.

🦎 Rufus 🦎 Rufus is a simple but powerful Denial of Service tool written in Python3. The type of the Dos attack is TCP Flood, the power of the attack

Billy 88 Dec 20, 2022
Tiny Interactive File Transfer Application

TIFTA: Tiny Interactive File Transfer Application This repository holds all the source code, tests and documentation of the TIFTA software. The main g

Jorge Martínez 2 Dec 08, 2021
SocksFlood, a DoS tools that sends attacks using Socks5 & Socks4

Information SocksFlood, a DoS tools that sends attacks using Socks5 and Socks4 Requirements Python 3.10.0 A little bit knowledge of sockets IDE / Code

ArtemisID 0 Dec 03, 2021