使用 TextFSM 查找中继上允许的 VLAN

Use TextFSM to find allowed VLANs on trunk

我正在尝试为 NTC ansible 设置一个 TextFSM 模板,它只会从 "show interface trunk" 命令的输出中提取主干上允许的 Vlan,似乎无法得到我想要的。它给了我所有的行,而不仅仅是我想要的一行。命令的输出如下所示:

switch#sh int g9/17 trunk

Port                Mode         Encapsulation  Status        Native vlan
Gi9/17              on           802.1q         trunking      1

Port                Vlans allowed on trunk
Gi9/17              501,503,513,540,950-957

Port                Vlans allowed and active in management domain
Gi9/17              501,503,513,540,950-957

Port                Vlans in spanning tree forwarding state and not pruned
Gi9/17              501,503,513,540,950-957

在此输出中,我只想 return "Vlans allowed on trunk" 下面的行,而不是其他具有相同信息的重复行。我的模板如下所示:

Value PORT (\S+)
Value VLANS (.*)

Start
  ^Port.*Vlans allowed on trunk -> Begin

Begin
  ^(?=\s{0,9}${PORT})\s+${VLANS} -> Record
  ^Port.*Vlans allowed and active in management domain -> End

使正则表达式更具体并得到想要的结果(也许:)。

import io
import textfsm

template = io.StringIO("""\
Value Port (\S+(/\d+)?)
Value Vlans (\d+([-,]\d+)+)

Start
  ^Port\s+Vlans allowed on trunk$$ -> Begin

Begin
  ^${Port}\s+${Vlans}$$ -> Record
  ^Port\s+Vlans allowed and active in management domain$$ -> End
""")
fsm = textfsm.TextFSM(template)
result = fsm.ParseText("""\
switch#sh int g9/17 trunk

Port                Mode         Encapsulation  Status        Native vlan
Gi9/17              on           802.1q         trunking      1

Port                Vlans allowed on trunk
Gi9/17              501,503,513,540,950-957

Port                Vlans allowed and active in management domain
Gi9/17              501,503,513,540,950-957

Port                Vlans in spanning tree forwarding state and not pruned
Gi9/17              501,503,513,540,950-957
""")
print(result)

[['Gi9/17', '501,503,513,540,950-957']]