import paramiko
import os
import datetime
import logging
from getpass import getpass
from pathlib import Path
import time
# Configure logging
logging.basicConfig(filename=’network_backup.log’, level=logging.INFO,
format=’%(asctime)s:%(levelname)s:%(message)s’)
class NetworkDevice:
def __init__(self, hostname, username, password, device_type):
self.hostname = hostname
self.username = username
self.password = password
self.device_type = device_type
def connect(self):
try:
logging.info(f”Connecting to {self.hostname}…”)
self.ssh_client = paramiko.SSHClient()
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh_client.connect(self.hostname, username=self.username, password=self.password)
logging.info(f”Successfully connected to {self.hostname}.”)
except Exception as e:
logging.error(f”Connection failed to {self.hostname}: {e}”)
raise
def get_configuration(self):
try:
logging.info(f”Retrieving configuration from {self.hostname}…”)
if self.device_type.lower() == ‘cisco’:
stdin, stdout, stderr = self.ssh_client.exec_command(‘show running-config’)
elif self.device_type.lower() == ‘juniper’:
stdin, stdout, stderr = self.ssh_client.exec_command(‘show configuration’)
else:
logging.error(“Unsupported device type.”)
return None
config = stdout.read().decode()
logging.info(f”Configuration retrieved from {self.hostname}.”)
return config
except Exception as e:
logging.error(f”Failed to retrieve configuration from {self.hostname}: {e}”)
return None
def disconnect(self):
self.ssh_client.close()
logging.info(f”Disconnected from {self.hostname}.”)
class BackupManager:
def __init__(self, backup_dir):
self.backup_dir = Path(backup_dir)
self.backup_dir.mkdir(parents=True, exist_ok=True)
def save_configuration(self, device, config):
timestamp = datetime.datetime.now().strftime(‘%Y%m%d_%H%M%S’)
filename = f”{device.hostname}_{device.device_type}_{timestamp}.cfg”
filepath = self.backup_dir / filename
with open(filepath, ‘w’) as f:
f.write(config)
logging.info(f”Configuration saved to {filepath}.”)
def main():
logging.info(“Network Backup Tool started.”)
# Get user input
devices = []
num_devices = int(input(“Enter number of devices to backup: “))
for _ in range(num_devices):
hostname = input(“Enter device hostname/IP: “)
username = input(“Enter SSH username: “)
password = getpass(“Enter SSH password: “)
device_type = input(“Enter device type (cisco/juniper): “)
devices.append(NetworkDevice(hostname, username, password, device_type))
backup_manager = BackupManager(backup_dir=’backups’)
for device in devices:
try:
device.connect()
config = device.get_configuration()
if config:
backup_manager.save_configuration(device, config)
device.disconnect()
except Exception as e:
logging.error(f”Error processing device {device.hostname}: {e}”)
logging.info(“Network Backup Tool finished.”)
if __name__ == “__main__”:
main()