Ansible。确定数组中最受欢迎的值

时间:2018-04-23 08:58:10

标签: python ansible cisco

 tasks:

   - name: Find popular vlan
     ios_command:
       provider: "{{ cli }}"
       commands:
         - show run | i switchport access vlan
     register: sh_res

   - debug: var=sh_res

Debug sh_res如下所示:

  "stdout_lines": [
            [
                "switchport access vlan 40", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 30", 
                " switchport access vlan 20", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22", 
                " switchport access vlan 22"
            ]
        ]
    }
}

我需要确定交换机上最受欢迎的vlan并输入变量{{vlan}}。在这种情况下它是22。 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

首先,你应该到达所有的vlan:

stdout_lines = sh_res['stdout_lines'][0]
vlans = [line.split()[-1] for line in stdout_lines] #['40', '22', ..., '22', '22']

之后你只需要在vlan中找到最常见的项目。来自集合的Check this topic.计数器可用于查找最常见的项目。

from collections import Counter

vlanCounter = Counter(vlans)
print(vlanCounter.most_common(1)) #[('22', 16)]
print(vlanCounter.most_common(1)[0][0]) #'22'