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

时间:2018-05-17 16:58:16

标签: python regex ansible text-parsing python-textfsm

我正在尝试为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

在这个输出中,我只想返回“在主干上允许的Vlans”下面的行,而不是返回具有相同信息的其他重复行。我的模板如下所示:

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

1 个答案:

答案 0 :(得分:0)

使正则表达式更具体,并获得所需的结果(可能:)。

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']]