The following script checks the CRC status of routers and switches to notify the system administrator via email in case there is CRC error on an interfaces.
In order to make it easier and more efficient to connect to routers and switches, we have created a file in YAML format that contains equipment information, IP, username and password, and IOS type, here is the YAML file:
Testbed:
name: alwaysonsbxs
credentials:
default:
username: "admin"
password: "ipcafe"
enable: "ipcafe"
devices:
csr1000v-1:
type: router
os: iosxe
connections:
ssh:
protocol: ssh
ip: 192.168.1.200
csr1000v-2:
type: router
os: iosxe
connections:
ssh:
protocol: ssh
ip: 192.168.1.201
First, we send the CLI commands to the routers using the Genie library, and we receive the result in JSON format. We also use the smtpli and email libraries to send emails.
from genie.conf import Genie
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Using the “for” loop, we connect to the devices which we specified in the testbed file, then we send the show interfaces command.
For more information about the genie library and what it supports -> https://pubhub.devnetcloud.com/media/genie-feature-browser/docs/#/
for device in testbed.devices:
testbed.devices[device].connect()
interface_details=testbed.devices[device].parse("show interfaces")
device_verstions[device]=verstion
device_interface_details[device]=interface_details
Converting the received results to our desired format by the help of 2 “for” loops, we define a condition to check the interfaces with crc error then we send the results to the sendmail function.
for device,interfaces in device_interface_details.items():
for interface, details in interfaces.items():
if details["counters"]["in_crc_errors"]==0:
continue
else:
sendmail(crc= details["counters"]["in_crc_errors"],interface=interface,device=device)
We send the email through an independent function as follows:
def sendmail(crc,interface,device):
from_addr='ipcafe@gmail.com'
to_addr='info@ipcafe.net'
msg=MIMEMultipart()
msg['From']=from_addr
msg['To']=",".join(to_addr)
msg['Subject']=f'{device}--Interface CRC Error'
body=f"device: {device} on{interface} have {crc} CRC Error"
msg.attach(MIMEText(body,'plain'))
smtp_server=smtplib.SMTP('smtp.gmail.com',587)
smtp_server.starttls()
smtp_server.login(''ipcafe@gmail.com”,”password”)
text=msg.as_string()
smtp_server.sendmail(from_addr,to_addr,text)
smtp_server.quit()
- Note: If you use gmail to send email in the script, you must first log in to the sender’s gmail account , then click on this url
https://www.google.com/settings/security/lesssecureapps and enable less secure applications option - you can use cron job for scheduling the script.
you can download the application source code and YAML file: Download
Password:ipcafe.net