Day #13 PyATS Series] Writing Your First pyATS Testscript (Simple Health Check) using pyATS for Cisco [Python for Network Engineer]

[Day #13 PyATS Series] Writing Your First pyATS Testscript (Simple Health Check) using pyATS for Cisco [Python for Network Engineer]


Introduction

In the evolving landscape of network engineering, automation has become essential. As a Python for Network Engineer practitioner, one of the best starting points is creating pyATS testscripts. These scripts allow you to automate health checks, validate network states, and ensure devices are functioning correctly without manual intervention.

This post is part of our 101 Days of pyATS (Vendor-Agnostic) series and is specifically focused on writing your first pyATS testscript for Cisco devices. We’ll cover a complete, hands-on example: performing a simple device health check (e.g., device reachability, interface status). You’ll learn how to set up your test environment, write a script, validate outputs, and understand the results. By the end, you’ll have the foundation to create more complex test suites and integrate them into production pipelines.


Topology Overview

For this example, we will use a basic lab with:

  • 1 Cisco Router (R1)
  • Management host running pyATS
  • SSH access for automation

Diagram

This is enough to demonstrate a device health check, and you can easily scale it to multiple devices.


Topology & Communications

  • Protocol: SSH
  • Transport: pyATS testbed file
  • Health Checks:
    • Device reachability
    • Interface admin/operational status
    • Device uptime and version

Communication flow:

  • Testbed loads device information → pyATS connects to device → Health check commands are executed → Results are reported.

Workflow Script

This script uses pyATS’ aetest framework to:

  1. Connect to the device
  2. Verify reachability
  3. Check interfaces
  4. Validate device uptime
from pyats import aetest
from genie.testbed import load
import logging

log = logging.getLogger(__name__)

class CommonSetup(aetest.CommonSetup):
    @aetest.subsection
    def connect_to_device(self, testbed):
        self.parent.parameters['device'] = testbed.devices['R1']
        self.parent.parameters['device'].connect(log_stdout=False)
        log.info('Successfully connected to R1')

class VerifyReachability(aetest.Testcase):
    @aetest.test
    def ping_test(self, device):
        result = device.ping('8.8.8.8')
        assert 'Success' in result, 'Ping test failed'

class VerifyInterfaces(aetest.Testcase):
    @aetest.test
    def check_interfaces(self, device):
        intf_info = device.learn('interface')
        for name, data in intf_info.info.items():
            assert data['enabled'] == True, f'{name} is administratively down'
            assert data['oper_status'] == 'up', f'{name} is operationally down'

class VerifyUptime(aetest.Testcase):
    @aetest.test
    def uptime_check(self, device):
        facts = device.learn('platform')
        uptime = facts.info['uptime']
        log.info(f'Device uptime: {uptime}')
        assert uptime > 0, 'Device uptime is zero'

class CommonCleanup(aetest.CommonCleanup):
    @aetest.subsection
    def disconnect(self, device):
        device.disconnect()

aetest.main(testbed='testbed.yml')

Explanation by Line

  • Imports: Brings in pyATS and Genie modules for test automation.
  • CommonSetup: Establishes SSH connection to the device before tests run.
  • VerifyReachability: Uses ping to verify external connectivity.
  • VerifyInterfaces: Learns interface states and asserts both admin and operational status.
  • VerifyUptime: Checks uptime to ensure device is stable.
  • CommonCleanup: Closes the session after tests complete.
  • aetest.main(): Entry point for pyATS test execution.

testbed.yml Example

testbed:
  name: Cisco_Lab
  devices:
    R1:
      os: iosxe
      type: router
      connections:
        cli:
          protocol: ssh
          ip: 192.168.1.101
      credentials:
        default:
          username: admin
          password: admin123

Post-validation CLI Screenshots (Expected Output)

When you run the script, you will see output like:

+------------------------------------------------------------------------------+
|                            Health Check Report                               |
+------------------------------------------------------------------------------+
VerifyReachability.ping_test ....... PASSED
VerifyInterfaces.check_interfaces .. PASSED
VerifyUptime.uptime_check .......... PASSED
------------------------------------------------------------------------------
Total Tests: 3   Passed: 3   Failed: 0
+------------------------------------------------------------------------------+

This confirms that the device is reachable, interfaces are up, and uptime is valid.


FAQs

Q1. What happens if one test fails?

A: If a test case fails, pyATS marks it as failed but continues executing the remaining tests. The final report summarizes total tests, passed/failed counts, and error messages. This granular reporting helps engineers quickly pinpoint problematic areas without halting the entire test run. You can also configure automated notifications or remediation actions based on these results.


Q2. What is a pyATS testscript?

A: A pyATS testscript is a structured Python file built using the aetest framework. It contains three main sections: setup, tests, and cleanup. The setup phase establishes device connections, the test cases execute health checks or validation tasks, and the cleanup phase ensures proper session termination. Testscripts automate common operational verifications like reachability, interface status, routing checks, and uptime verification. This approach reduces manual CLI usage and allows repeatable, scalable network validations across multiple environments.


Q3: Can we use this script for multiple devices?

A: Yes. pyATS is designed to work with testbeds that include multiple devices. By adding more devices to your testbed.yml, you can loop through them dynamically or use parallel execution (pcall) to run health checks simultaneously. This allows network engineers to validate hundreds of devices efficiently in large enterprise networks or data centers.


Q4: Does this script require configuration changes on the device?

A: No configuration changes are required. The testscript operates in a read-only manner, connecting via SSH and running show commands to gather data. This makes it safe for production environments since it doesn’t alter running configurations or disrupt services. It’s ideal for pre/post-change validations or routine monitoring without impacting device operations.


Q5: How can I view detailed logs for each test?

A: pyATS supports various log levels (info, debug, warning, error). When executing the script, you can specify --loglevel debug to see verbose output. This includes detailed device interaction logs, parsed outputs, and pass/fail statuses. These logs are stored in the results directory, enabling engineers to troubleshoot issues or analyze test runs over time.


Q6: Can we add more checks like CPU, memory, or BGP sessions?

A: Absolutely. pyATS and Genie provide parsers to learn operational states such as CPU usage, memory utilization, BGP neighbor relationships, and even QoS statistics. You can add additional test cases to your script to collect and validate these parameters. Over time, you can build comprehensive health checks covering the entire device stack, improving network reliability and reducing manual audits.


Q7: Is pyATS free to use?

A: Yes. Cisco offers pyATS and Genie as free, open-source Python libraries. Engineers can install them without licensing costs, making it accessible for labs and production networks. Being open-source, pyATS has a growing community that contributes parsers, plugins, and documentation to accelerate automation adoption.


Q8: How do I schedule these health checks?

A: You can schedule testscript executions using Linux cron jobs, Windows Task Scheduler, or orchestration tools like Jenkins, GitLab CI/CD, or Ansible Tower. Scheduled runs provide continuous monitoring, allowing automated health checks during maintenance windows or daily operational cycles. Integrating results into dashboards or sending email alerts helps proactively detect and resolve issues.


YouTube Link

Watch the Complete Python for Network Engineer: Writing Your First pyATS Testscript (Simple Health Check) 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

Learning how to build pyATS testscripts is just the beginning. To become proficient in Python for Network Engineer automation, you need structured guidance and real-world practice.

Trainer Sagar Dhawan offers a 3-month instructor-led training covering Python, Ansible, API integrations, and Cisco DevNet skills. This program is designed for network engineers who want to master automation tools and advance their careers.

Join the training here and take your first step towards becoming a network automation expert.

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