如何用CiscoConfParse获取Cisco IOS中GigabitEthernet1/3的IP?报错解决
如何通过CiscoConfParse获取GigabitEthernet1/3接口的IP地址
目标IOS配置
! hostname Example ! interface GigabitEthernet1/1 description Example interface ip address 192.0.2.1 255.255.255.128 no ip proxy-arp ! interface GigabitEthernet1/2 shutdown ! interface GigabitEthernet1/3 ip address 192.0.2.129 255.255.255.128 no ip proxy-arp ! end
错误代码及报错信息
尝试以下代码时触发AttributeError:
from ciscoconfparse2 import CiscoConfParse config = """! hostname Example ! interface GigabitEthernet1/1 description Example interface ip address 192.0.2.1 255.255.255.128 no ip proxy-arp ! interface GigabitEthernet1/2 shutdown ! interface GigabitEthernet1/3 ip address 192.0.2.129 255.255.255.128 no ip proxy-arp ! end """ parse = CiscoConfParse(config.splitlines(), syntax='ios', factory=False) intf = parse.find_objects("interface GigabitEthernet1/3")[0] print(f"GigabitEthernet1/3 address: {intf.ipv4}")
报错内容:
AttributeError: The ipv4 attribute does not exist
错误原因
初始化CiscoConfParse时设置了factory=False,此时返回的是普通配置行文本对象,没有封装ipv4这类便捷属性。只有启用factory=True(默认值,可省略)时,才会生成带属性的接口对象。
解决方法
方法一:启用Factory模式(推荐)
去掉factory=False(或显式设置factory=True),接口对象会自带ipv4属性:
from ciscoconfparse2 import CiscoConfParse config = """! hostname Example ! interface GigabitEthernet1/1 description Example interface ip address 192.0.2.1 255.255.255.128 no ip proxy-arp ! interface GigabitEthernet1/2 shutdown ! interface GigabitEthernet1/3 ip address 192.0.2.129 255.255.255.128 no ip proxy-arp ! end """ # 默认启用Factory模式,无需设置factory参数 parse = CiscoConfParse(config.splitlines(), syntax='ios') intf = parse.find_objects("interface GigabitEthernet1/3")[0] # ipv4属性返回(IP地址, 子网掩码)元组 ip_addr, subnet_mask = intf.ipv4 print(f"GigabitEthernet1/3 address: {ip_addr}/{subnet_mask}")
方法二:不启用Factory模式,手动提取配置
若必须使用factory=False,可通过匹配子配置行提取IP:
from ciscoconfparse2 import CiscoConfParse config = """! hostname Example ! interface GigabitEthernet1/1 description Example interface ip address 192.0.2.1 255.255.255.128 no ip proxy-arp ! interface GigabitEthernet1/2 shutdown ! interface GigabitEthernet1/3 ip address 192.0.2.129 255.255.255.128 no ip proxy-arp ! end """ parse = CiscoConfParse(config.splitlines(), syntax='ios', factory=False) intf = parse.find_objects("interface GigabitEthernet1/3")[0] # 匹配接口下的ip address配置行 ip_line = intf.find_child_objects(r"ip address")[0] # 拆分字符串提取IP和掩码 _, ip_addr, subnet_mask = ip_line.text.split() print(f"GigabitEthernet1/3 address: {ip_addr}/{subnet_mask}")
内容的提问来源于stack exchange,提问作者Mike Pennington
相关产品推荐
相关产品推荐

