Netmiko脚本报错:'str'对象无'readlines'属性,求问题排查
问题分析与解决方法
错误原因
Netmiko的send_command('show running-config')返回的是字符串对象,而readlines()是文件对象专属的方法,直接对字符串调用这个方法自然会触发AttributeError: 'str' object has no attribute 'readlines'。
修正方案
- 替换遍历方式:用字符串的
splitlines()方法替代readlines(),它能把配置字符串按换行符分割成列表,实现逐行遍历的需求。 - 调整打印逻辑:原代码里的print语句写在循环内部,会导致每遍历一行就输出一次结果,逻辑错误,应该把判断后的打印放在循环结束之后。
修正后的完整代码
output4 = net_connect.send_command('show running-config') console_logging = False # 用splitlines()分割字符串为行列表 for line in output4.splitlines(): if line.startswith("logging"): console_logging = True break # 循环结束后再判断输出 if console_logging: print('Logging console is enabled') else: print('logging console is not enabled') net_connect.disconnect()
内容的提问来源于stack exchange,提问作者Jimmy
相关产品推荐
相关产品推荐

