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
Install Required Libraries:
pip install netmiko pandas openpyxl
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_type | host | username | password | secret | port |
---|---|---|---|---|---|
cisco_ios_telnet | 192.168.1.1 | admin | password | enable_password | 23 |
cisco_ios_telnet | 192.168.1.2 | admin | password | enable_password | 2323 |
Updated Script
Here's the updated script to save the configuration file using the hostname:
Explanation
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.
Read Device Information:
- Read the Excel file using
pandas.read_excel()
and convert the DataFrame to a list of dictionaries.
- Read the Excel file using
Output Directory:
- Define the directory where the configuration files will be saved and create it if it doesn’t exist.
Commands:
- Define a list of commands to be executed on each device.
Current Date:
- Get the current date in the format
YYYY-MM-DD
.
- Get the current date in the format
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 theConnectHandler
method. - Retrieve the hostname using the command
show running-config | include hostname
.
- Define a function
Loop Through Devices:
- Loop through the list of devices and call
connect_and_save
for each device.
- Loop through the list of devices and call
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
Post a Comment