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)

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

To include the Telnet port information for each device and read this information from an Excel file, you can modify the script accordingly. Here's how you can update the script to handle different Telnet ports for each device.

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

Script to Automate Login and Save Configuration

Here's the updated script to handle different Telnet ports:

python Script 

As Above mentioned.

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, runs the commands, and saves the output to a file.
    • Extract the port information from the device dictionary and use it in the ConnectHandler method.
  7. Loop Through Devices:

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

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

Popular posts from this blog

MPLS L2 VPN Types

Multiple Cisco device configuration Backup using python Script

Profile Based IKEv1 GRE Tunnel Configuration in Huawei Router