读取CSV执行Cisco命令时遇AttributeError:列表无strip属性
解决Netmiko批量执行命令的两个问题:AttributeError与仅处理最后一个IP
问题1:AttributeError: 'list' object has no attribute 'strip'
- 原因:
csv.reader读取的每一行row是一个列表(例如['172.16.X.X']),而Netmiko的host参数要求传入字符串类型。直接把row赋值给host会导致Netmiko调用strip()方法时出错——列表没有这个字符串方法。 - 解决:取列表的第一个元素
row[0]作为主机IP,同时跳过CSV的表头行(第一行的IP文本)。
问题2:脚本仅处理最后一个IP
- 原因:原脚本中,命令结果判断、文件保存、设备断开连接的代码都在
for循环外部,循环结束后只会使用最后一次循环的row和output执行后续操作。 - 解决:将这些代码缩进,放到
for循环内部,确保每个IP对应的操作都能完整执行。
修正后的完整脚本
from netmiko import ConnectHandler import getpass import csv usr = input("Enter your Username: ") passwd = getpass.getpass('Please Enter Password: ') command = input('Enter Cmd You Wish to Send: ') with open('Scripts/SWList.csv', 'r') as csv_list: switches = csv.reader(csv_list) next(switches) # 跳过CSV表头行('IP'那一行) for row in switches: # 提取列表第一个元素并去除首尾空格,确保是合法IP字符串 host_ip = row[0].strip() Cisco_Switches = { 'device_type': 'cisco_ios', 'host': host_ip, 'username': usr, 'password': passwd } try: # 建立设备连接 device = ConnectHandler(**Cisco_Switches) # 发送命令并获取输出 output = device.send_command(command) # 判断命令执行结果 if '% Unknown command' in output: print(f'Error Sending Command for {host_ip}!') else: print(f'Command Sent Successfully to {host_ip}...') # 保存输出到对应IP的文件中 filename = f'Scripts/{host_ip}.txt' with open(filename, "a") as save_file: save_file.write(output) # 断开设备连接 device.disconnect() except Exception as e: # 捕获并打印连接或执行命令时的异常 print(f'Failed to connect to {host_ip}: {str(e)}')
关键修正点说明
- 用
next(switches)跳过CSV表头行,避免尝试连接IP这个无效主机名。 - 通过
row[0].strip()提取并格式化IP地址,确保传入Netmiko的host是合法字符串。 - 将所有单设备操作(连接、发命令、结果判断、存文件、断连接)移入
for循环,保证每个IP都执行完整流程。 - 添加
try-except块捕获异常,避免单个设备出错导致整个脚本中断。 - 使用f-string替代字符串拼接,简化代码并提升可读性。
- 用
with open(...)自动管理文件关闭,避免手动关闭可能引发的资源泄漏问题。
内容的提问来源于stack exchange,提问作者BennyOverlord
相关产品推荐
相关产品推荐

