如何修改Cisco交换机备份脚本,遇认证失败时跳过对应IP
Cisco交换机备份脚本异常处理优化
原脚本在遇到交换机凭证错误时会抛出paramiko.ssh_exception.AuthenticationException并终止程序,以下是修改后的代码,可实现跳过异常IP、继续处理后续设备的功能:
import sys import time import paramiko import datetime now = datetime.datetime.now() user = input("Enter username:") password = input("Enter Paswd:") enable_password = input("Enter enable pswd:") port=22 # 用with语句自动管理文件生命周期,避免提前关闭 with open('myswitches.txt') as f0: for ip in f0.readlines(): ip = ip.strip() # 跳过空行 if not ip: continue filename_prefix = '/Users/apple/Documents/' + ip ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: # 尝试连接并执行备份操作 ssh.connect(ip, port, user, password, look_for_keys=False) chan = ssh.invoke_shell() time.sleep(2) chan.send('enable\n') chan.send(enable_password +'\n') time.sleep(1) chan.send('term len 0\n') time.sleep(1) chan.send('sh run\n') time.sleep(20) output = chan.recv(999999) # 生成备份文件并写入内容 filename = "%s_%.2i%.2i%i_%.2i%.2i%.2i" % (ip, now.year, now.month, now.day, now.hour, now.minute, now.second) with open(filename, 'a') as f1: f1.write(output.decode("utf-8")) print(f"成功备份交换机 {ip}") ssh.close() except paramiko.ssh_exception.AuthenticationException: print(f"交换机 {ip} 认证失败,跳过该设备") ssh.close() continue except Exception as e: print(f"处理交换机 {ip} 时发生未知错误: {str(e)}") ssh.close() continue
关键修改说明
- 异常捕获机制:用
try-except块包裹SSH连接及备份核心逻辑,专门捕获认证异常,同时兜底处理其他未知异常,确保程序不会中断 - 文件管理优化:使用
with语句自动处理文件打开/关闭,修复原脚本中f0.close()放在循环内导致后续IP无法读取的问题 - 错误提示:增加控制台输出,明确标注异常设备IP,方便后续排查
- 空行过滤:跳过IP文件中的空行,避免无效连接尝试
内容的提问来源于stack exchange,提问作者Pablo
相关产品推荐
相关产品推荐

