Network Automation Script for Cisco IOS devices

This Python script is a network automation script that uses the netmiko library to connect to a Cisco IOS device, execute a series of commands specified in a file, and then save the outputs to a file. Let’s break down the code:

Libraries

import netmiko
import re
import sys
# from getpass import getpass
# from queue import Queue
# import signal
# signal.signal(signal.SIGFPE,signal.SIG_DFL)
# signal.signal(signal.SIGINT,signal.SIG_DFL)
  • The script imports necessary libraries:
  • netmiko: A multi-vendor library to simplify Paramiko SSH connections to network devices.
  • re: Regular expression operations for pattern matching.
  • sys: Provides access to some variables used or maintained by the interpreter.
  • There are commented-out lines related to getting passwords securely, handling signals, and using a queue. They are not used in the current script.

Function Definitions

# Function definitions are not provided in this script.
  • The script does not define any functions.

Variable Declarations

device = {
        "ip" :"10.10.10.3",
        "device_type" : "cisco_ios",
        "username" : "cisco",
        "password" : "cisco"
        }
commands_file = "commands"
outputs = []
  • The script initializes a dictionary device with details like IP address, device type, username, and password for connecting to the Cisco IOS device.
  • commands_file is set to “commands,” and an empty list outputs is initialized to store the outputs of executed commands.

Main Code

ipaddress = input("Enter IP Address : \n")
username = input("Enter username : \n")
password = input("Enter password : \n")
commands_file = input("Enter filename for commands : \n")
device = {
        "ip" :ipaddress,
        "device_type" : "cisco_ios",
        "username" : username,
        "password" : password
        }
timeout_duration = 60
  • The script takes user input for IP address, username, password, and the filename containing commands. It then updates the device dictionary with the provided input.
try:
    print(f'Connecting to device {device["ip"]}')
    connection = netmiko.ConnectHandler(**device)  # establishing SSH connection
    connection.send_command('ter len 0')
    hostname = re.search(r"hostname (.+)", connection.send_command('sh run | include hostname'))
  • The script attempts to connect to the Cisco IOS device using the netmiko.ConnectHandler method. It also sets terminal length to 0 and retrieves the hostname using a regular expression.
    with open(commands_file+'.txt', 'r') as file:
        commands = file.readlines()
        for command in commands:
            print("\nexecuting command :- "+command+"\n")
            try:
                out = connection.send_command(command, read_timeout=timeout_duration)
                print(out)
                outputs.append(out)
            except (netmiko.exceptions.ReadTimeout) as readout_error:
                print(f"Executing command : {command} takes more than {timeout_duration} seconds. Program returned a Readout Error")
                print("Saving outputs to file...")
                # sys.exit()
    connection.disconnect()
    with open(hostname.group(1)+'.txt', 'w') as result:
        result.writelines("ATP Results for " + hostname.group(1))
        result.writelines("\n================================================================================")
        for output in outputs:
            result.writelines("\noutput of command :" + commands[outputs.index(output)]+'\n')
            result.writelines("--------------------------------------------------------------------------------\n")
            result.writelines(output)
            result.writelines("\n================================================================================")
  • The script opens the specified commands file, reads the commands, and executes each command on the connected device. It captures the outputs and appends them to the outputs list.
except (netmiko.exceptions.NetmikoAuthenticationException,
        netmiko.exceptions.NetmikoTimeoutException) as error:
    error_message = re.match(".*", str(error)).group(0)
    print(f'Cannot connect to {device["ip"]} due to {error_message}')
    print('================================================================================')
  • The script handles exceptions related to authentication and timeout errors during the connection attempt.

This script is designed to automate the process of connecting to a Cisco IOS device, executing commands specified in a file, and saving the outputs to a file named after the hostname. Note that the script assumes a specific format for the command file and may need adjustments based on your specific use case.

Add a Comment

Your email address will not be published. Required fields are marked *