[Day #31 PyATS Series] Detect VLAN Mismatches on Trunk Links Using pyATS for Cisco [Python for Network Engineer]

[Day #31 PyATS Series] Detect VLAN Mismatches on Trunk Links Using pyATS for Cisco [Python for Network Engineer]

Introduction

Detecting VLAN mismatches on trunk links is crucial for maintaining seamless Layer 2 connectivity across a network. A VLAN mismatch can lead to traffic drops, inconsistent broadcast domains, and ultimately network instability. Traditional troubleshooting involves manually logging into each switch and comparing trunk configurations—a slow, error-prone process.

In today’s 101 Days of pyATS (Vendor-Agnostic) series, Trainer Sagar Dhawan demonstrates how to automate VLAN mismatch detection using pyATS. This tutorial is designed for Python for Network Engineer learners who want to:

  • Automate trunk VLAN validation across Cisco switches
  • Quickly identify mismatches and misconfigurations
  • Scale VLAN consistency checks to large enterprise networks
  • Generate structured, actionable reports

By the end of this guide, you’ll have a reusable pyATS solution that can integrate into CI/CD pipelines for proactive VLAN health monitoring.


Topology Overview

Our network consists of three Cisco switches connected via trunk links:

  • Switch1 trunk to Switch2
  • Switch2 trunk to Switch3
  • VLANs 10, 20, and 30 should be consistently allowed across all trunks.

Topology & Communications

  • Protocol: 802.1Q trunking
  • Authentication: Configured in testbed.yml
  • Execution: CLI connections via SSH

Steps:

  1. Connect to each switch.
  2. Run show interfaces trunk command.
  3. Parse allowed VLANs and operational trunk state.
  4. Compare VLAN lists between neighbor switches.

Workflow Script

from genie.testbed import load
import json

def get_trunk_vlans(device):
    device.connect(log_stdout=False)
    output = device.parse('show interfaces trunk')
    device.disconnect()

    trunks = {}
    for iface, details in output['interface'].items():
        allowed = details.get('vlans_allowed', '')
        trunks[iface] = allowed
    return trunks

def compare_vlans(device_trunks):
    mismatches = []
    devices = list(device_trunks.keys())
    for i in range(len(devices) - 1):
        d1, d2 = devices[i], devices[i+1]
        for iface1, vlans1 in device_trunks[d1].items():
            for iface2, vlans2 in device_trunks[d2].items():
                if vlans1 != vlans2:
                    mismatches.append({
                        'device_pair': f"{d1}-{d2}",
                        'interfaces': f"{iface1}-{iface2}",
                        'vlans': f"Mismatch: {vlans1} vs {vlans2}"
                    })
    return mismatches

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

    trunk_data = {}
    for name, device in devices.items():
        print(f"Collecting trunk VLANs from {name}...")
        trunk_data[name] = get_trunk_vlans(device)

    mismatches = compare_vlans(trunk_data)

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

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

Explanation by Line

  • get_trunk_vlans function: Connects to each switch, runs show interfaces trunk, extracts allowed VLANs per trunk interface.
  • compare_vlans function: Compares VLANs on trunk interfaces between adjacent switches to identify mismatches.
  • Main block: Loops through switches, collects trunk VLAN info, and generates a mismatch report.

testbed.yml Example

testbed:
  name: vlan_mismatch_test
  devices:
    Switch1:
      os: iosxe
      type: switch
      connections:
        cli:
          protocol: ssh
          ip: 192.168.101.1
      credentials:
        default:
          username: admin
          password: cisco123

    Switch2:
      os: iosxe
      type: switch
      connections:
        cli:
          protocol: ssh
          ip: 192.168.101.2
      credentials:
        default:
          username: admin
          password: cisco123

    Switch3:
      os: iosxe
      type: switch
      connections:
        cli:
          protocol: ssh
          ip: 192.168.101.3
      credentials:
        default:
          username: admin
          password: cisco123

Post-validation CLI Screenshots (Expected Output)

Switch1:

Switch1# show interfaces trunk
Port    Vlans allowed on trunk
Gi0/1   10,20,30

Script Output:

[
  {
    "device_pair": "Switch1-Switch2",
    "interfaces": "Gi0/1-Gi0/1",
    "vlans": "Mismatch: 10,20,30 vs 10,20"
  }
]

8. FAQs

1. Can this script detect VLAN pruning differences on trunk links?

Yes. The script compares the allowed VLANs on each trunk interface and flags any discrepancies, including cases where VLANs are pruned on one side but not the other.


2. Does this solution handle VLAN ranges like 10-20 automatically?

Yes. pyATS Genie parsers normalize VLAN ranges into explicit VLAN lists, enabling accurate comparisons of trunk configurations.


3. How does the script identify which interfaces are trunk links?

The script uses the parsed output from show interfaces trunk, which lists all interfaces configured as trunks and their allowed VLANs.


4. Is it safe to run VLAN mismatch checks during production hours?

Yes. The script only executes read-only commands and does not modify any VLAN or trunk configurations on the devices.


5. Can I scale this validation for dozens of switches?

Absolutely. pyATS supports connecting to multiple devices concurrently. By adding more devices to testbed.yml, you can scale the validation to large networks.


6. How can I visualize and track VLAN mismatches over time?

You can store the JSON output in a monitoring tool or database, and visualize VLAN mismatch trends using dashboards like Grafana or Kibana.


7. Will this script work for non-Cisco network devices?

With appropriate parsers or vendor-specific show commands, the script can be extended to Arista, Palo Alto, Fortinet, and other multi-vendor environments.


8. Can this be extended to automatically correct VLAN mismatches?

Yes. With additional automation logic, you can standardize VLAN configurations and push corrections via pyATS or Ansible playbooks to resolve mismatches automatically.


YouTube Link

Watch the Complete Python for Network Engineer: Detect VLAN mismatches on trunk links 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

Automating VLAN mismatch detection saves hours of manual troubleshooting and prevents costly outages. Trainer Sagar Dhawan offers a 3-month instructor-led program teaching Python, Ansible, APIs, and Cisco DevNet for Network Engineers. Gain hands-on experience with pyATS to automate VLAN checks and more.

Join Our Training to advance your career and master Python for Network Engineer skills.

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