如何从 Cisco IOS 配置获取接口 IP 地址?

问题描述 投票:0回答:1

使用以下 Cisco IOS 配置时,如何通过

GigabitEthernet1/3
获取
CiscoConfParse()
的接口 IP 地址?

!
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 ciscoconfparse 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...

AttributeError: The ipv4 attribute does not exist
python cisco ciscoconfparse
1个回答
0
投票

有两种技术可以做到这一点:

  • 要访问Cisco IOS接口的
    ipv4
    属性,需要使用
    factory=True
    进行解析;这会返回一个
    IPv4Obj()
  • 您还可以从
    find_child_objects()
    factory=False
    获取字符串形式的 IP 地址。

factory=True 和
ipv4
属性

明确...

from ciscoconfparse 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=True)
intf = parse.find_objects("interface GigabitEthernet1/3")[0]
print(f"GigabitEthernet1/3 address: {intf.ipv4}")
$ python example.py
GigabitEthernet1/3 address: <IPv4Obj 192.0.2.129/25>
$

请注意,

factory=True
功能尚处于实验阶段。

factory=False 和
find_child_objects()

您还可以通过使用

factory=False
解析并使用
find_child_objects()
...

获取接口 IP 地址作为字符串
>>> from ciscoconfparse import CiscoConfParse, IPv4Obj
>>> 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)
>>> obj = parse.find_child_objects("interface GigabitEthernet1/3", "ip address")[0]
>>> addr = obj.re_match("ip\saddress\s(\S.+)")
>>> addr
'192.0.2.129 255.255.255.128'
>>> IPv4Obj(addr)
<IPv4Obj 192.0.2.129/25>
>>>
© www.soinside.com 2019 - 2024. All rights reserved.