通过输出解析

时间:2019-05-22 10:08:52

标签: python bash parsing

我想创建一个虚拟IP值列表。一个接口可能有一个或多个虚拟地址。 (192.168.1.1,192.168.2.1,192.168.3.1)

[Switch] disp vrrp verbose interface Vlan-interface 1 | begin Virtual_IP
     Virtual IP     : 192.168.1.1
                      192.168.2.1
     Master IP      : 0.0.0.0
     VRName         :
     Follow Name 

[Switch] disp vrrp verbose interface Vlan-interface2 | begin Virtual_IP
     Virtual IP     : 192.168.3.1
     Master IP      : 0.0.0.0
     VRName         :
     Follow Name    :

我试图首先使用.split函数和字符串“ Master”作为分隔符来分割输出。然后,我将使用第一个列表项,并再次使用“:”作为分隔符。现在,第二个列表项包含:

192.168.1.1 192.168.2.1

当我现在再次使用\ n作为分度符将其拆分时,我会收到三个项目 192.168.1.1 192.168.2.1并留有空白标签或空白

我也许可以遍历最后一个列表,然后“删除”空白,换行和制表符。

这种好方法是否有更好的方法来获得相同的结果?

2 个答案:

答案 0 :(得分:0)

此脚本可以完成任务。在此示例中,文本在测试文件中:

ip=$(grep '192.168' ./test | tr -d "Virtual IP\:")
echo $ip

答案 1 :(得分:0)

我已经通过使用其他方法解决了这个问题。首先捕获整个命令输出,而不用管道将其输出到设备本身。

output = connection.send_command('display vrrp verbose interface vlan-interface1')

然后使用带有范围的splitlines(),提取了“有趣的”行。

lines = output.splitlines()[10:-3]

然后将每一行分割成多个单词并检查它们的内容,就有两种匹配的可能,或者只有一个1个单词:

words = line.split()

    if len(words) == 1:
        #If only single word is returned then it is a VIP
        print('Words is equal to 1')
        vip = words[0]
        vips.append(vip)

或者还有第二个包含字符串“ IP”的项目

 elif words[1] == 'IP':
    #If multiple words are returned the 2nd will contain
    #IP vs MAC string
    print('Words Item 2 is qual to IP')
    vip = words[-1]
    vips.append(vip)

结果,vip列表将包含一个或多个所有VIP。