ansible使用之——网络设备自动巡检

ansible网络设备自动巡检

  • 前言
  • 环境搭建
  • 过程演练
  • 结果验证

前言

一般中大型公司需要对网络设备进行定期巡检,当设备量比较大且巡检指标较多的时候,该项工作往往费时费力,同时如果完全采用人工巡检的话,还容易出现人为因素上的失误。
通过ansible工具对网络设备进行自动化巡检,可以提高工作效率并且降低人为因素的失误。

本博客以ansible自动巡检华为ensp模拟设备,通过检查设备“是否开启snmp配置”为例,讲解网络设备高效巡检过程,相关输入参数如下:
ansible版本: 2.8.1
设备厂商: 华为路由器
主控节点: Centos7服务器

环境搭建

网络环境(拓扑):
ansible使用之——网络设备自动巡检_第1张图片
设备清单:

  • R1:10.0.1.1(管理ip)
  • R2:10.0.2.2(管理ip)
  • R3:10.0.3.3(管理ip)

控制环境:
操作系统: CentOS7
ansible: 2.8.1 (此处采用docker自定义镜像,详情可参考我另外的博客《CentOS安装指定版本应用(ansible)》、《docker安装部署ansible并打包》、《ansible使用之——国产设备适配》、《配置华为设备ssh登录实现网络设备与VMWare虚拟机信息交互》)

过程演练

  1. 编辑inventory文件hosts
[devices]
10.0.1.1
10.0.2.2
10.0.3.3

[devices:vars]
ansible_ssh_user: huawei
ansible_ssh_pass: Josen@12345

ansible使用之——网络设备自动巡检_第2张图片

  1. 编辑ansible脚本hello.yml
---
- hosts: devices
  vars:
    ansible_connection: network_cli
    ansible_ssh_user: huawei
    ansible_ssh_pass: "Josen@12345"
    ansible_network_os: vrp2
    ansible_become: no
  tasks:
    - name: hello 
      cli_command:
        command: "dis cur | include snmp"
      register: run
    - name: debug
      debug:
        msg: "{{ run.stdout | get_snmp }}"
  1. 编辑filter
import textfsm

class FilterModule(object):

    def filters(self):
        return {
            'get_snmp': get_snmp
        }

def get_snmp(data):
    fsm_path = '/opt/ansible/plugins/textfsm/snmp.fsm'
    with open(fsm_path, 'r') as fr:
        fsm = textfsm.TextFSM(fr)
    res = fsm.ParseTextToDicts(data)
    print(res)
    if res:
        result = {"result": "yes"}
    else:
        result = {"result": "the device has not config the snmp"}
    return result

ansible使用之——网络设备自动巡检_第3张图片
textfsm文件

Value community (.+)
Value version (.+)

Start
  ^snmp-agent community read cipher ${community}
  ^snmp-agent sys-info version ${version}

ansible使用之——网络设备自动巡检_第4张图片

结果验证

执行ansible-playbook -i hosts hello.yml,结果如下:
ansible使用之——网络设备自动巡检_第5张图片

你可能感兴趣的:(python,ansible,自动化运维,1024程序员节,ansible,华为,python,自动化巡检)