Python Script to Pull Interface Status – Your First Step into Network Automation [CCNP ENTERPRISE]

Python Script to Pull Interface Status – Your First Step into Network Automation [CCNP ENTERPRISE]_networkjourney

Today we’re going to take a solid, practical step into real-world network automation using Python. One of the most common and beginner-friendly tasks is to pull interface status from network devices — and trust me, this is the exact use case that sparks automation journeys for many network engineers.

You don’t need to be a Python expert. You just need the curiosity to simplify your repetitive tasks. Imagine instead of logging into 10 routers manually to check if interfaces are up, you could run one script and get everything on your screen (or a CSV file). That’s the power of using Python with libraries like Netmiko, Paramiko, or NAPALM.

Let’s not just talk theory — let me show you how it works, walk you through the logic, give you lab config, and even troubleshoot the common gotchas. Ready? Let’s dive in.


Theory in Brief – What Are We Automating?

The Pain of Manual Checks

In a typical enterprise setup, you often need to verify interface statuses — whether they’re up or down, which ports are flapping, which are shut. Traditionally, you would SSH into each device, run show ip interface brief, and note the results. It’s not scalable.


The Power of Python

With Python and libraries like Netmiko, you can automate SSH sessions and run CLI commands on multiple devices in one go. You can extract the output, filter it, log it, or even send alerts. This automation not only saves time but reduces human errors.

The best part? You don’t need SNMP or REST APIs here — pure CLI automation. If your device supports SSH, you’re good to go.


Key Python Libraries to Know

  • Netmiko – For SSH-based automation, supports multiple platforms like Cisco, Juniper, HP
  • Paramiko – Low-level SSH, more flexibility but complex
  • TextFSM – For parsing CLI output into structured data
  • Pandas – (Optional) for reporting and CSV generation

Comparision– Script Use Case, Libraries, Pros & Cons

FeatureDetails
Use CasePulling interface status using Python
Target DevicesCisco IOS, IOS XE, Nexus, etc.
Protocol UsedSSH
Required LibrariesNetmiko, TextFSM (optional), Pandas (optional)
Output FormatCLI, CSV, JSON (customizable)
Auth TypeUsername & Password or SSH keys

Pros and Cons

ProsCons
Easy to write and extendParsing raw CLI can be tricky without TextFSM
Works with legacy CLI-based devicesLimited to SSH, not API-based
Portable and lightweightNeeds Python installed and tested with libraries
Perfect for quick auditing and monitoringParsing format varies across device models

Essential CLI Commands (Used in Script)

PurposeCLI CommandNotes
Interface summaryshow ip interface briefMost common to check status and IP
All interface detailshow interfacesGives detailed stats including bandwidth
Interface errorsshow interfaces counters errorsUseful to detect CRC, input/output errors
Interface descriptionsshow interfaces descriptionHelpful to correlate with topology
Interface brief by protocolshow interfaces statusNexus-style devices

Real-World Use Case

ScenarioHow Python HelpsOutcome
Daily interface health checkRuns script on all routersSaves hours vs manual SSH
Detect down or administratively shut portsParses status fieldTriggers alerts for critical links
Inventory auditCaptures IP, description, statusBuilds an inventory or documentation
Change verification post-deploymentChecks if new links are upActs as a post-check for rollout automation
Scheduled monitoringCron-based Python scriptGenerates daily/weekly health reports

EVE-NG Lab – Interface Status Script Demo

Lab Topology Diagram


Device Configuration (Router R1 and R2)

hostname R1
!
interface g0/0
ip address 192.168.1.1 255.255.255.0
no shutdown
!
interface g0/1
ip address 10.0.0.1 255.255.255.0
shutdown
!
username admin privilege 15 password cisco123
ip domain-name netjourney.local
crypto key generate rsa
ip ssh version 2
line vty 0 4
transport input ssh
login local

Repeat similar config for R2 with different IPs.


Sample Python Script (Netmiko)

from netmiko import ConnectHandler
import csv

devices = [
{
'device_type': 'cisco_ios',
'host': '192.168.1.1',
'username': 'admin',
'password': 'cisco123',
},
{
'device_type': 'cisco_ios',
'host': '192.168.1.2',
'username': 'admin',
'password': 'cisco123',
}
]

output_list = []

for device in devices:
net_connect = ConnectHandler(**device)
print(f"Connecting to {device['host']}")
output = net_connect.send_command("show ip interface brief")
print(output)
output_list.append((device['host'], output))
net_connect.disconnect()

# Save to CSV
with open('interface_status.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Device IP", "Interface Output"])
for entry in output_list:
writer.writerow(entry)

Troubleshooting Tips

IssueProbable CauseFix
Script can’t connect to routerSSH not enabled or IP wrongCheck SSH setup and management IP
Authentication failedWrong credentialsUse correct username/password
Output is garbled or emptyDevice output differs from expected formatValidate output manually first
Python error – No module foundMissing libraryInstall with pip install netmiko
Connection timeoutRouter not reachable from hostCheck routing, firewall, and EVE-NG connectivity

Most Common FAQs

1. Why should I automate interface status checks using Python?

Answer:
Manually logging into multiple network devices to check interface status is time-consuming and error-prone. With Python, you can automate this task across hundreds of devices, saving time, ensuring consistency, and reducing human error. It’s also a great first step toward more complex automation like configuration changes or compliance checks.


2. What libraries do I need for writing a Python script to pull interface status?

Answer:
For CLI-based devices (like Cisco IOS), you can use:

  • Netmiko – For SSHing into devices and running CLI commands
  • TextFSM – For parsing raw CLI output into structured data

For API-enabled devices (like Cisco IOS XE or NX-OS):

  • Requests – For sending REST API calls
  • JSON – For handling API responses

These libraries make it simple to interact with devices programmatically.


3. How does Netmiko help in pulling interface data?

Answer:
Netmiko is a Python library that simplifies SSH connectivity to network devices.
It supports many vendors including Cisco, Juniper, Arista, etc.
You can use it to:

  • SSH into a device
  • Run show ip interface brief or show interfaces
  • Capture the output and parse it

Example:

from netmiko import ConnectHandler

device = {
'device_type': 'cisco_ios',
'ip': '192.168.1.1',
'username': 'admin',
'password': 'cisco'
}

conn = ConnectHandler(**device)
output = conn.send_command("show ip interface brief")
print(output)

4. How do I parse the output of show ip interface brief into structured data?

Answer:
You can use TextFSM, which converts CLI text into structured tables.
When used with Netmiko, it can automatically parse commands if templates are available.

output = conn.send_command("show ip interface brief", use_textfsm=True)
for intf in output:
print(intf['interface'], intf['ip_address'], intf['status'])

This makes it easy to generate reports, dashboards, or trigger alerts.


5. What is an example of using Python with REST APIs to get interface status?

Answer:
For REST-enabled devices like Cisco IOS XE, you can use this example with the requests library:

import requests
requests.packages.urllib3.disable_warnings()

url = "https://192.168.1.1/restconf/data/ietf-interfaces:interfaces"
headers = {
'Content-Type': 'application/yang-data+json',
'Accept': 'application/yang-data+json'
}
response = requests.get(url, auth=("admin", "cisco"), headers=headers, verify=False)
print(response.json())

This will return a JSON structure with all interfaces and their statuses.


6. Can I pull interface status from multiple devices at once?

Answer:
Yes, using Python loops or multithreading, you can query multiple devices in one script. Here’s a simplified version using Netmiko:

devices = ['192.168.1.1', '192.168.1.2']
for ip in devices:
device = {
'device_type': 'cisco_ios',
'ip': ip,
'username': 'admin',
'password': 'cisco'
}
conn = ConnectHandler(**device)
output = conn.send_command("show ip interface brief", use_textfsm=True)
print(f"--- {ip} ---")
for intf in output:
print(intf['interface'], intf['status'])

For large-scale environments, consider using concurrent.futures or multiprocessing for better performance.


7. How can I save the interface status output to a CSV or Excel file?

Answer:
You can use Python’s csv or pandas library:

import csv

with open('interface_status.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Device', 'Interface', 'IP Address', 'Status'])
for intf in output:
writer.writerow(['192.168.1.1', intf['interface'], intf['ip_address'], intf['status']])

This allows you to generate audit-ready reports in seconds.


8. What are common errors while automating with Netmiko or REST APIs?

Answer:
Some common issues include:

  • Authentication failures – due to wrong credentials or enable password
  • Device unreachable – due to wrong IP or SSH disabled
  • Command parsing issues – if output format differs by platform or version
  • Certificate warnings – when using REST APIs with HTTPS
    You can handle these using try-except blocks and verify=False for REST calls (for labs only).

9. Do I need a DevNet certification to write Python network automation scripts?

Answer:
Not at all! While DevNet certification is valuable, you can start automation with basic Python skills.
Understanding:

  • Variables, loops, functions
  • How to use pip to install libraries like Netmiko or Requests
  • Basic networking concepts like SSH, IP, and interfaces
    …is enough to get started. DevNet just helps formalize and advance your skills.

10. How can I make this script production-ready?

Answer:
To make your Python automation script ready for production:

  • Add logging instead of just print statements
  • Use YAML/JSON files for device inventory
  • Add error handling and retry logic
  • Use secure vaults (like Ansible Vault or environment variables) for credentials
  • Schedule it using cron jobs or task schedulers
    These improvements make your script reliable, secure, and scalable.

YouTube Link

Watch the Complete CCNP Enterprise: Python Script to Pull Interface Status – Your First Step into Network Automation Lab Demo & Explanation on our channel:

Class 1 CCNP Enterprise Course and Lab Introduction | FULL COURSE 120+ HRS | Trained by Sagar Dhawan
Class 2 CCNP Enterprise: Packet Flow in Switch vs Router, Discussion on Control, Data and Management
Class 3 Discussion on Various Network Device Components
Class 4 Traditional Network Topology vs SD Access Simplified

Final Note

Understanding how to differentiate and implement Python Script to Pull Interface Status – Your First Step into Network Automation is critical for anyone pursuing CCNP Enterprise (ENCOR) certification or working in enterprise network roles. Use this guide in your practice labs, real-world projects, and interviews to show a solid grasp of architectural planning and CLI-level configuration skills.

If you found this article helpful and want to take your skills to the next level, I invite you to join my Instructor-Led Weekend Batch for:

CCNP Enterprise to CCIE Enterprise – Covering ENCOR, ENARSI, SD-WAN, and more!

Get hands-on labs, real-world projects, and industry-grade training that strengthens your Routing & Switching foundations while preparing you for advanced certifications and job roles.

Emailinfo@networkjourney.com
WhatsApp / Call: +91 97395 21088

Upskill now and future-proof your networking career!


Trainer Sagar Dhawan

Hi all,
Good to see you here.
I'm your Trainer for CCIE, CCNP, CCNA, Firewall batches and many more courses coming up!
Stay tuned for latest updates!
Keep me posted over Whatsapp/Email about your experience learning from us.
Thanks for being part of - "Network Journey - A journey towards packet-life!!!"