思科未关闭的ios iOS,关机接口

问题描述

这是我当前的剧本

---
- hosts: SWITCHES
  gather_facts: no

  tasks:
  - name: Show Interface Status
    ios_command:
    commands:
        - show int status 
    register: out

  - debug: var=out.stdout_lines

我基本上想使用此脚本,然后禁用所有处于“ notconnect”状态的端口,这意味着所有未连接任何端口的端口。有没有一种方法可以向此接口添加“ when”语句,以便当“ show interface status”返回时,它查看所有未连接的端口,并通过对每个接口应用“ shutdown”命令来禁用这些端口?我认为我需要做一个“何时”声明,但是不确定从哪里开始。还是有更好的方法来做到这一点?

是否有一个可以完成此操作的python脚本?

解决方法

您应该使用ios_facts检索包含所有接口的字典。然后,您可以遍历该词典以关闭未连接的接口。

如果使用-vvv开关运行剧本,您将看到ios_facts收集的所有变量。

我相信Ansible 2.9及更高版本,如果您指定“ gather_facts:yes”,则Ansible会收集实际的网络设备事实。对于Ansible 2.8或更早版本,您需要使用“ ios_facts”模块。

---
- hosts: SWITCHES
  gather_facts: no

  tasks:
  - name: gather IOS facts
    ios_facts:

  - name: Shutdown notconnect interfaces
    ios_config:
      lines: shutdown
      parents: "interface {{ item.key }}"
    with_dict: "{{ ansible_net_interfaces }}"
    when: item.value.operstatus == "down"

以下是收集的“ ansible_net_interfaces”变量中的一部分示例:

{
    "ansible_net_interfaces": {
        "GigabitEthernet0/0": {
            "bandwidth": 1000000,"description": null,"duplex": "Full","ipv4": [],"lineprotocol": "down","macaddress": "10b3.d507.5880","mediatype": "RJ45","mtu": 1500,"operstatus": "administratively down","type": "RP management port"
        },"GigabitEthernet1/0/1": {
            "bandwidth": 1000000,"duplex": null,"lineprotocol": null,"macaddress": "10b3.d507.5881","mediatype": "10/100/1000BaseTX","operstatus": "down","type": "Gigabit Ethernet"
        },"GigabitEthernet1/0/10": {
            "bandwidth": 1000000,"description": "Telefon/PC","macaddress": "null,"GigabitEthernet1/0/11": {
            "bandwidth": 1000000,"macaddress": "10b3.d507.588b","type": "Gigabit Ethernet"
        }
    }

"ansible_net_interfaces"变量的值是一个字典。该词典中的每个键都是接口名称,值是一个包含新键/值对的新词典。未连接接口时,"operstatus"键的值为"down"

"with_dict"任务中使用"ios_config"循环遍历字典中的所有顶级键/值对,并且您可以通过引用{{1}来使用每个键/值对中的变量}或“ "{{ item.key }}"

{{ item.value }}"任务中使用"when",为执行任务设置条件。在这种情况下,我们只希望它在"ios_config"的值为"operstatus"时运行。

"down"任务中的"parents"参数指定要在其中输入配置的新部分,在这种情况下,该部分是接口配置模式。使用"ios_config"变量为"ansible_net_interfaces"中的每个接口返回接口名称。

有关这些模块的信息,请参阅Ansibles文档,以更好地理解它们: https://docs.ansible.com/ansible/latest/collections/cisco/ios/ios_facts_module.html https://docs.ansible.com/ansible/latest/collections/cisco/ios/ios_config_module.html