用 Python 实现网络设备自动化巡检

背景

公司有华为交换机和路由器等网络设备 20 多台,网络管理员小李每日需对这些网络设备进行巡检(巡检设备单板状态、cpu 使用率、cpu 温度、系统告警日志等),掌握设备工作状态,提前预防,并及时发现问题,以确保网络设备工作正常。该公司并未购买和使用自动化监控软件,需网络管理员小李通过手工方式 SSH 登录网络设备,查看网络设备健康状况,手工方式巡检增加了小李很多重复工作,费时费力,工作效率低下,现小李准备使用 Python 编程语言,编写简易的自动化巡检脚本来代替每日手工巡检,提高工作效率。

知识点

通过本项目可以掌握如下知识点和技能点,同时积累项目经验。

  • Python 编程环境的配置方法。
  • Python 语言基本使用方法。
  • Paramiko 模块的使用方法。
  • 利用 Python 实现简单的自动化巡检方法。
  • 项目拓扑

    该拓扑中只模拟了部分交换机设备,使用网管终端对交换机 SW1-SW5 进行自动化巡检。

    项目规划

    本项目的核心任务是使用 Paramiko 模块完成网络设备自动化巡检,为保持项目的完整性,需完成前期准备工作。

  • 配置 IP 地址:在交换机 SW1-SW5 上配置远程管理 IP。
  • 启用 SSH:在交换机 SW1-SW5 上开启 SSH。
  • 安装软件:在网管终端上安装 Python 编程环境。
  • 编写巡检设备信息文档。
  • 编写设备巡检命令文档。
  • 编写巡检程序。
  • 项目实施

    配置 IP 地址

    在交换机 SW1-SW5 配置远程管理 IP(这里仅以其中 1 台交换机为例配置)。

    <SW1>system
    [SW1]interface Vlanif 1
    [SW1-Vlanif1]ip address 192.168.10.11 24
    [SW1-Vlanif1]quit
    [SW1]interface GigabitEthernet 0/0/1
    [SW1-GigabitEthernet0/0/1]port link-type trunk
    [SW1-GigabitEthernet0/0/1]port trunk allow-pass vlan all
    

    启用 SSH

    [SW1]undo telnet server enable
    Warning: The operation will stop the Telnet server. Continue? [Y/N]:y
    [SW1]rsa local-key-pair create 
    The key name will be: SW1_Host
    The range of public key size is (512 ~ 2048). 
    NOTES: If the key modulus is greater than 512, 
     it will take a few minutes.
    Input the bits in the modulus[default = 512]:2048
    Generating keys...
    ................................................................................
    ..+++
    .............................................+++
    .++++++++
    .........................++++++++
    [SW1]user-interface vty 0 4
    [SW1-ui-vty0-4]authentication-mode aaa
    [SW1-ui-vty0-4]protocol inbound ssh
    [SW1-ui-vty0-4]quit
    [SW1]aaa
    [SW1-aaa]local-user admin password cipher Huawei@123
    [SW1-aaa]local-user admin service-type ssh
    [SW1-aaa]quit
    [SW1]ssh user admin service-type stelnet
    Info: Succeeded in adding a new SSH user.
    [SW1]ssh user admin authentication-type password
    [SW1]stelnet server enable
    Info: Succeeded in starting the Stelnet server.
    [SW1]quit
    <SW1>save
    The current configuration will be written to the device.
    Are you sure to continue?[Y/N]y
    Info: Please input the file name ( *.cfg, *.zip ) [vrpcfg.zip]:
    Jan 30 2020 15:25:18-08:00 SW1 %%01CFM/4/SAVE(l)[6]:The user chose Y when decidi
    ng whether to save the configuration to the device.
    

    安装软件(以 windows 为例)

    在 Python 官方网站下载 Windows 安装包,下载完成后,双击安装即可。注意在高级选项中,要选中“Add Python to environment variable”选项,其他步骤保存默认设置即可。安装完成后,在系统命令行窗口输入【Python】命令即可进入 Python 命令行界面。

    编写巡检设备信息文档。

    将巡检设备的信息(IP 地址、用户名、密码),写入 device_info.txt 文档。当巡检程序执行时,程序会从 device_info.txt 读取设备的信息,用于连接设备。device_info.txt 文档内容如下所示,第一列为设备管理地址,第二列为 SSH 登录用户名,第三列为登录密码,信息之间用逗号隔开“,”。这里只列出了部分设备的信息,如果需要增加巡检设备,在文档中继续添加即可。

    192.168.10.11,admin,Huawei@123
    192.168.10.12,admin,Huawei@123
    192.168.10.13,admin,Huawei@123
    192.168.10.14,admin,Huawei@123
    192.168.10.15,admin,Huawei@123
    

    编写设备巡检命令文档。

    列出日常巡检内容需要的巡检命令,写入 cmd.txt 巡检命令文档。如需增加巡检内容,在文档中增加相应的内容即可。巡检程序执行并连接设备成功后,程序会读取 cmd.txt 中的巡检命令,收集设备信息。

    display device
    display environment
    display alarm urgen
    display memory-usage
    display cpu-usage
    display logbuffer level 0
    display logbuffer level 1
    display logbuffer level 2
    display logbuffer level 3
    display logbuffer level 4
    

    编写巡检程序。

    # 导入模块
    import paramiko
    import time
    # 读取巡检设备信息
    dev_filepath = r"d:\Python\device_info.txt"
    dev_file = open(dev_filepath,"r")
    while 1: 
     ##每次读取文件中一行信息
     dev_info = dev_file.readline()
     if not dev_info :
     break
     else :
     ##读取设备 IP,用户名和密码并赋值给变量
     devs = dev_info.split(',') 
     ip = devs[0]
     username = devs[1]
     password = devs[2].strip()
     password = password.strip('\n')
    # 读取巡检命令
    cmd_filepath = r"d:\Python\cmd.txt"
    cmd_file = open(cmd_filepath,"r")
    cmds = cmd_file.readlines()
    # 远程连接设备
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=ip,username=username,password=password)
    print("成功连接",ip)
    #发送巡检命令
    command = ssh.invoke_shell()
    for line in cmd:
    command.send(cmd+'\n')
    #保存巡检结果
    output=command.recv(65535)
    str_output=str(output)
    outprint=str_output.strip().split('\\r\\n')
    log=open("d:\Python\py\xunjian\\"+ip+".txt",'a')
    log.write(start_info+'\n\n'+str(outprint)+'\n\n'+end_info)
    log.close()
    

    完善并形成完整巡检程序

    #-*- coding:UTF-8 -*-
    import paramiko
    import time
    starttime = time.strftime('%Y-%m-%d %T')
    start_info = "巡检开始时间:"+str(starttime)
    cmd_filepath = r"d:\Python\py\xunjian\cmd.txt"
    cmd_file = open(cmd_filepath,"r")
    cmds = cmd_file.readlines()
    dev_filepath = r"d:\Python\py\xunjian\device_info.txt"
    dev_file = open(dev_filepath,"r")
    while 1: 
     dev_info = dev_file.readline()
     if not dev_info :
     break
     else :
     devs = dev_info.split(',') 
     ip = devs[0]
     username = devs[1]
     password = devs[2].strip()
     password = password.strip('\n')
     ssh = paramiko.SSHClient()
     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     ssh.connect(hostname = ip,username = username,password = password)
     print("成功连接",ip)
     command = ssh.invoke_shell()
     time.sleep(3)
     command.send('N\n') #该行非必须
     command.send('screen-length 0 temporary\n') #取消分屏显示
     for cmd in cmds:
     command.send(cmd+'\n')
     time.sleep(5)
     output = command.recv(65535).decode()
     log = open(r"d:\Python\py\xunjian\\"+ip+".txt",'a')
     endtime = time.strftime('%Y-%m-%d %T')
     end_info = "巡检结束时间:"+str(endtime)
     log.write(start_info+'\n\n'+output+'\n\n'+end_info)
     log.close()
    dev_file.close()
    

    项目验证

    查看生成的设备巡检文档

    运行巡检程序,巡检结束后,将在目录下生成以设备 IP 地址命名巡检文档,如图所示。

    查看巡检文档的内容

    交换机 SW1(IP:192.168.10.11)巡检文档的内容如下:

    巡检开始时间:2020-01-30 22:23:31
    ' ---------------------------------------------', 
    'User last login information: ',
    '-----------------------------------------------', 
    'Access Type: SSH', 
    'IP-Address : 192.168.10.11 ssh', 
    'Time: 2020-01-30 22:23:55-08:00',
    ' ---------------------------------------------',
    '<SW1>display device', 
    "S3700-26C-HI's Device status:",
    'Slot Sub Type Online Power Register Status Role ', 
    '-----------------------------------------------------------------------',
    '0 - 3726C Present PowerOn Registered Normal Master',
    '<SW1>display environment', 
    'Environment information:',
    'Temperature information:',
    'SlotID CurrentTemperature LowLimit HighLimit',
    ' (deg c ) (deg c) (deg c )', 
    '0 0 0 70', 
    '<SW1>display alarm urgen',
    'Alarm: ',
    'Alarm Slot Date Time Location',
    '-----------------------------------------------------',
    'Temp low 0 2020/01/30 22:23:59 Slot 0',
    'Fan abnormal 0 2020/01/30 22:23:59 Slot 0',
    '<SW1>display memory-usage',
    ......
    巡检结束时间:2020-01-30 22:23:37
    

    作者:热爱技术的小胡

    物联沃分享整理
    物联沃-IOTWORD物联网 » 用 Python 实现网络设备自动化巡检

    发表回复