Multiple Cisco device configuration Backup using python Script

 Multiple Cisco device configuration Backup using python Script

Device configuration will be saved as per Hostname.

 

 Saved files are looking as below:

 ===================
 Python Script:
=================== 
from netmiko import ConnectHandler
import pandas as pd
import datetime
import os

# Read device information from the Excel file
device_file = "devices.xlsx"
devices_df = pd.read_excel(device_file)

# Convert the dataframe to a list of dictionaries
devices = devices_df.to_dict(orient='records')

# Directory to save the configuration files
output_directory = "device_configs"
os.makedirs(output_directory, exist_ok=True)

# Define the commands to be executed
commands = [
'show running-config',
'show ip interface brief',
'show version'
]

# Get the current date
current_date = datetime.datetime.now().strftime("%Y-%m-%d")


# Function to connect to a device and save the output to a file
def connect_and_save(device):
try:
# Extract port and remove it from the device dictionary
port = device.pop('port')

# Establish Telnet connection with the specified port
net_connect = ConnectHandler(**device, port=port)

# Enter enable mode
net_connect.enable()

# Get the hostname
hostname = net_connect.send_command('show running-config | include hostname').split()[1]

# Initialize an empty string to hold the output
device_output = ""

# Execute each command and capture the output
for command in commands:
output = net_connect.send_command(command)
device_output += f"\n{command}:\n{output}\n"

# Generate the filename using the hostname
filename = f"{hostname}_{current_date}.txt"
filepath = os.path.join(output_directory, filename)

# Save the output to the file
with open(filepath, "w") as file:
file.write(device_output)

print(f"Configuration saved for {hostname} to {filepath}")

# Close the connection
net_connect.disconnect()
except Exception as e:
print(f"An error occurred with device {device['host']}: {e}")


# Connect to each device and save the configuration
for device in devices:
connect_and_save(device)

========================================================================

To save the configuration file with the device's hostname instead of the IP address, you need to retrieve the hostname from each device during the session and then use it to name the configuration file. Here’s how you can modify the script to achieve this:

Prerequisites

  1. Install Required Libraries:

  1. pip install netmiko pandas openpyxl
  2. Prepare an Excel File: Create an Excel file (e.g., devices.xlsx) with the following columns: device_type, host, username, password, secret, port. Each row should contain the connection details for a device.

Example Excel File (devices.xlsx)

device_typehostusernamepasswordsecretport
cisco_ios_telnet192.168.1.1adminpasswordenable_password23
cisco_ios_telnet192.168.1.2adminpasswordenable_password2323

Updated Script

Here's the updated script to save the configuration file using the hostname:

python Script:

As above

Explanation

  1. Import Libraries:

    • netmiko: For Telnet and SSH connections.
    • pandas: To read the Excel file.
    • datetime: To get the current date.
    • os: To create directories and manage file paths.
  2. Read Device Information:

    • Read the Excel file using pandas.read_excel() and convert the DataFrame to a list of dictionaries.
  3. Output Directory:

    • Define the directory where the configuration files will be saved and create it if it doesn’t exist.
  4. Commands:

    • Define a list of commands to be executed on each device.
  5. Current Date:

    • Get the current date in the format YYYY-MM-DD.
  6. Function to Connect and Save Configuration:

    • Define a function connect_and_save that connects to a device, retrieves the hostname, runs the commands, and saves the output to a file named with the hostname and the current date.
    • Extract the port information from the device dictionary and use it in the ConnectHandler method.
    • Retrieve the hostname using the command show running-config | include hostname.
  7. Loop Through Devices:

    • Loop through the list of devices and call connect_and_save for each device.

Notes

  • Hostname Retrieval: The script assumes that the show running-config | include hostname command will return the hostname in a format where the second word is the hostname (e.g., hostname Router1). Adjust the parsing if your device's output differs.
  • Error Handling: The script includes basic error handling to print an error message if the connection to a device fails.
  • Enable Mode: The script enters enable mode before executing the commands. Ensure that the enable password is provided correctly.
  • Security: Avoid hardcoding passwords in the script for production environments. Consider using secure methods to handle credentials (e.g., environment variables, encrypted storage).

This script will read the device information, including the Telnet port, from an Excel file, log in to each device, execute the specified commands, retrieve the hostname, and save the output to a file named with the device’s hostname and the current date.

 

Comments

Popular posts from this blog

MPLS L2 VPN Types

Profile Based IKEv1 GRE Tunnel Configuration in Huawei Router