Scenario: You have multiple IDF in each building in your organization, you don’t want to do manually take configuration of network switches, you can automate this process by simple steps using python.
To automate weekly backups of the Juniper or Cisco switch configuration over SSH, you can achieve this using a simple script along with a scheduler (Task Scheduler on Windows or cron
on Linux). Here’s a step-by-step guide to setting this up:
Prerequisites
- SSH Access: Ensure SSH access is set up and you can log in without manual password input by configuring SSH keys. (Make sure that user account has read access to configuration not modify access)
- We use Windows Desktop or Server and Juniper Switches.
- Install Python: Download and install Python from https://www.python.org/downloads/.
- Python and Paramiko: Python installed with the Paramiko library for SSH automation.
- Install Paramiko: Open Command Prompt and run:
pip install paramiko
Step 1: Create Python Script to Backup Configuration
Here’s a sample script that logs into the switch, runs the show configuration | display set
command, and saves the output to a file with a timestamp.
import paramiko
import time
from datetime import datetime
import os
# Device details
host = 'YourSwitchIP' # Replace with your switch IP
username = 'YourUsername' # Replace with your SSH username
password = 'YourPassword' # Replace with your SSH password
backup_dir = r'C://path/to/backup' # Directory to save backups
def backup_config():
# Ensure backup directory exists
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
# Establish SSH connection
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, username=username, password=password)
print(f"Connected to {host}")
# Open a session
session = ssh.invoke_shell()
time.sleep(1)
# Send the command to display configuration in set format
session.send("show configuration | display set | no-more\n")
time.sleep(5) # Wait for the output to be fully returned
# Receive output
output = session.recv(65535).decode('utf-8')
# Create a timestamped backup file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_file = os.path.join(backup_dir, f"juniper_backup_{host}_{timestamp}.txt")
with open(backup_file, 'w') as file:
file.write(output)
print(f"Backup saved to {backup_file}")
except Exception as e:
print(f"An error occurred: {e}")
finally:
ssh.close()
# Run the backup function
if __name__ == '__main__':
backup_config()
Step 2: Create Batch File
@echo off
REM Full path to the Python executable
set PYTHON_PATH="C:\Users\youraccount\AppData\Local\Programs\Python\Python313\python.exe"
REM Full path to the Python script
set SCRIPT_PATH="C:\Path\To\YourScript_Switch_autobackup.py"
REM Log file to capture output and errors (optional)
set LOG_FILE="C:\logs\backup_log.txt"
%PYTHON_PATH% %SCRIPT_PATH% >> %LOG_FILE% 2>&1
Save this as backupswitchtask.bat
Step 3: Create Task Schedular to Schedule the Script
Open Task Scheduler:
- Press
Win + R
, typetaskschd.msc
, and press Enter.
Create a New Task:
- Click “Create Basic Task…”.
- Name it (e.g., “Switch Weekly Backup”) and click Next.
Set the Schedule:
- Choose “Weekly” and set your preferred day and time (e.g., every Friday at 9 PM).
- Click Next.
Set the Action:
- Select “Start a Program” and click Next.
- Browse to the Windows Batch executable file (e.g.,
C:\backupswitchtask.bat
).
Security Considerations
- Use SSH Keys: Instead of storing passwords in the script, consider configuring SSH keys for more secure, password-less authentication.
- Restrict Access: Ensure the script and backup files are only accessible by authorized users.
- Encryption: Consider encrypting the backup files if they contain sensitive information.
This setup should automate your weekly Juniper configuration backups efficiently!