通过outpu解析

2024-09-28 22:10:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个虚拟IP值列表。可能存在一个或多个与接口关联的虚拟地址。(192.168.1.1192.168.2.1192.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 你知道吗

当我现在使用delimeter再次拆分它时,我收到三个项目 192.168.1.1 192.168.2.1和空制表符或空白

我也许可以遍历最后一个列表并“删除”空白、新行和制表符。你知道吗

这种方法好吗?有没有更好的方法来获得同样的结果?你知道吗


Tags: nameipmaster列表verbosevirtualinterfacebegin
2条回答

这个脚本可以完成任务。在本例中,文本位于测试文件中:

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

我用不同的方法解决了这个问题。首先捕获整个命令输出,而无需将其传输到设备本身。你知道吗

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

然后使用splitlines()和range,我提取了“有趣的”线。你知道吗

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

然后把每一行分成几个单词,检查它们的内容,有两种可能匹配,或者只有一个单词:

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,一个或多个。你知道吗

相关问题 更多 >