Multiple Cisco device Backup Python Script using Telnet with different port
Multiple device Backup Python Script using Telnet with different port
File will be saved using Device IP address
Need to create a xl file the same file location as named device
Create an Excel file (e.g., devices.xlsx
)
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 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()
# 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
filename = f"{device['host']}_{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 {device['host']} 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)
===============================================
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 |
Script to Automate Login and Save Configuration
Here's the updated script to handle different Telnet ports:
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, runs the commands, and saves the output to a file. - Extract the
port
information from the device dictionary and use it in theConnectHandler
method.
- 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
- 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 updated script reads the device information, including the Telnet port, from an Excel file, logs in to each device, executes the specified commands, and saves the output to a file named with the device’s IP address and the current date.
Comments
Post a Comment