[Day #24 PyATS Series] BGP Neighbor Validation (Multi-Vendor) Using pyATS for Cisco

[Day #24 PyATS Series] BGP Neighbor Validation (Multi-Vendor) Using pyATS for Cisco [Python for Network Engineer]

Introduction

Border Gateway Protocol (BGP) is the backbone of modern enterprise and service provider networks, enabling scalable routing between different autonomous systems. Validating BGP neighbor relationships across a multi-vendor environment is critical for ensuring routing stability and avoiding outages. Traditionally, engineers log into each device and manually verify BGP sessions—a process prone to human error. With pyATS, you can automate BGP neighbor validation across Cisco, Arista, Juniper, Palo Alto, and Fortinet devices in a single run.

This article, tailored for Python for Network Engineer learners, walks through automating BGP peer validation using pyATS. By the end, you’ll have a vendor-agnostic script that quickly verifies BGP peering states, detects missing sessions, and reports inconsistencies, making your network more robust and future-proof.


Topology Overview

We’ll demonstrate this with the following simplified topology:

  • Router1 (Cisco IOS-XE) – AS 65001
  • Router2 (Cisco IOS-XR) – AS 65002
  • Switch1 (Arista EOS) – AS 65001
  • Firewall1 (Palo Alto) – AS 65003
  • Fortigate1 (Fortinet) – AS 65004

Our goal is to validate BGP neighbor relationships across all these devices, regardless of vendor.


Topology & Communications

  • Protocol: SSH for CLI-based checks
  • pyATS Genie parsers: Used to parse show bgp or show ip bgp summary
  • Authentication: Managed via testbed.yml

The script will:

  1. Connect to each device
  2. Run vendor-appropriate BGP commands
  3. Parse neighbor information (state, prefixes, uptime)
  4. Report neighbors that are not established
  5. Optionally, validate expected neighbor IPs and AS numbers

Workflow Script

from genie.testbed import load
import json

def get_bgp_neighbors(device):
    device.connect(log_stdout=False)
    if device.os in ['iosxe', 'iosxr']:
        output = device.parse('show ip bgp summary')
    elif device.os == 'eos':
        output = device.parse('show ip bgp summary')
    elif device.os == 'panos':
        output = device.parse('show routing protocol bgp')
    elif device.os == 'fortinet':
        output = device.parse('get router info bgp summary')
    else:
        output = {}
    device.disconnect()
    return output

def summarize_bgp(output):
    summary = {}
    for neighbor_ip, details in output.get('neighbors', {}).items():
        state = details.get('state_pfxrcd', 'unknown')
        prefixes = details.get('prefix_received', 0)
        summary[neighbor_ip] = {
            'state': state,
            'prefixes_received': prefixes
        }
    return summary

if __name__ == "__main__":
    testbed = load('testbed.yml')
    devices = testbed.devices
    bgp_report = {}

    for name, device in devices.items():
        print(f"Checking BGP neighbors on {name}...")
        neighbor_output = get_bgp_neighbors(device)
        bgp_report[name] = summarize_bgp(neighbor_output)

    with open('bgp_neighbor_report.json', 'w') as f:
        json.dump(bgp_report, f, indent=4)

    print(json.dumps(bgp_report, indent=4))

Explanation by Line

  • Imports: Loads testbed and JSON for output.
  • get_bgp_neighbors():
    • Connects to device and runs OS-specific BGP command.
    • Uses Genie parser to structure data.
  • summarize_bgp(): Extracts neighbor state and prefixes received.
  • Main block: Iterates through all devices and builds a consolidated BGP report.

This allows multi-vendor validation without separate scripts for each vendor.


testbed.yml Example

testbed:
  name: bgp_neighbor_validation
  devices:
    Router1:
      os: iosxe
      type: router
      connections:
        cli:
          protocol: ssh
          ip: 192.168.200.1
      credentials:
        default:
          username: admin
          password: cisco123

    Router2:
      os: iosxr
      type: router
      connections:
        cli:
          protocol: ssh
          ip: 192.168.200.2
      credentials:
        default:
          username: admin
          password: cisco123

    Switch1:
      os: eos
      type: switch
      connections:
        cli:
          protocol: ssh
          ip: 192.168.200.3
      credentials:
        default:
          username: admin
          password: arista123

    Firewall1:
      os: panos
      type: firewall
      connections:
        cli:
          protocol: ssh
          ip: 192.168.200.4
      credentials:
        default:
          username: admin
          password: paloalto123

    Fortigate1:
      os: fortinet
      type: firewall
      connections:
        cli:
          protocol: ssh
          ip: 192.168.200.5
      credentials:
        default:
          username: admin
          password: fortinet123

Post-validation CLI Screenshots (Expected Output)

Cisco IOS-XE:

Router1# show ip bgp summary
Neighbor        V    AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
192.168.200.2   4 65002     100     120        5    0    0 1d02h    20

Arista EOS:

Switch1# show ip bgp summary
Neighbor        AS    MsgRcvd MsgSent   Up/Down  State/PfxRcd
192.168.200.1   65001     200     220    3d04h   25

Palo Alto:

> show routing protocol bgp
BGP neighbor 192.168.200.1 Established, prefixes received: 18

Script Output:

{
    "Router1": {"192.168.200.2": {"state": "20", "prefixes_received": 20}},
    "Switch1": {"192.168.200.1": {"state": "25", "prefixes_received": 25}},
    "Firewall1": {"192.168.200.1": {"state": "Established", "prefixes_received": 18}}
}

FAQs

1. How does the script handle different vendor BGP outputs?

pyATS Genie uses vendor-specific parsers to interpret the output of BGP commands. This ensures you get consistent data structures for all vendors (Cisco, Arista, Palo Alto, Fortinet) without writing multiple scripts.

2. Can the script detect BGP neighbor session flaps and instability?

Yes. By running the script periodically and analyzing the Up/Down time fields, you can detect neighbors that are frequently resetting or flapping, aiding proactive troubleshooting.

3. How can I validate BGP neighbor AS numbers and authentication settings?

You can extend the script to include checks for expected AS numbers and authentication parameters. Any mismatches can be flagged in the generated report.

4. Can I integrate this validation into a CI/CD pipeline?

Absolutely. You can run the script as part of a CI/CD job (e.g., Jenkins or GitHub Actions) and have it automatically fail builds or trigger alerts if BGP sessions are not in an established state.

5. Does this script support IPv6 BGP neighbor checks?

Yes. As long as IPv6 BGP peers are configured and the vendor parser supports it, pyATS can capture and validate IPv6 neighbor states seamlessly.

6. Is it possible to visualize BGP neighbor health in a dashboard?

Yes. Export the JSON output from this script to monitoring systems like Grafana or Kibana to create real-time dashboards showing session health and prefixes received.

7. How scalable is this solution for large multi-vendor environments?

pyATS can handle connections to hundreds of devices concurrently. For very large networks, you can leverage multiprocessing or distributed job execution to scale efficiently.

8. Is the script safe to run in production?

Yes. The script uses only read-only show commands, ensuring that no configuration changes occur on production devices.


YouTube Link

Watch the Complete Python for Network Engineer: BGP Neighbor Validation (Multi-Vendor) Using pyATS for Cisco [Python for Network Engineer] Lab Demo & Explanation on our channel:

Master Python Network Automation, Ansible, REST API & Cisco DevNet
Master Python Network Automation, Ansible, REST API & Cisco DevNet
Master Python Network Automation, Ansible, REST API & Cisco DevNet
Why Robot Framework for Network Automation?

Join Our Training

Mastering BGP validation is crucial for modern network engineers managing hybrid and multi-vendor environments. Trainer Sagar Dhawan offers a 3-month instructor-led course covering Python, Ansible, APIs, and Cisco DevNet for Network Engineers. Gain hands-on experience automating BGP validation and much more.

Join the Training Here and enhance your skills with Python for Network Engineer expertise to excel in network automation.

Enroll Now & Future‑Proof Your Career
Emailinfo@networkjourney.com
WhatsApp / Call: +91 97395 21088