银狐NetDevOps-网络运维Python初篇(四)netmiko抓取华为网络配置并存入本地

1、训练场景:读取excel中设备IP地址,通过Netmiko抓取设备配置,并存入本地

上一小节我们通过excel得到设备IP地址,并用Netmiko批量抓取设备配置并打印出来,真实运维场景我们需要把这些输出的内容储存起来,这也是我们本章的练习。

2、实验环境:

操作系统:windows 10 PC机

python版本:python 3.8

网络设备:华为CE 6865

编辑器:vscode(pycharm、sublime均可,推荐vscode)

excel格式:初次使用简单一些,excel中只加入IP地址

[图片上传失败...(image-660304-1621267283375)]

3、思路分析

大部分都是上一小节内容,需要注意的是把配置文件存储到本地时,我们需要打上一个时间戳,今天执行任务和明天执行代码的配置要存入不同的文件夹,比如今天生成的配置就存在2021-02-08的文件件下,明天生成的配置都存入2021-02-09的文件件下。

4、整体代码

#!/usr/bin/env python
#coding: utf-8

import os
from time import time
from datetime import datetime
from netmiko import ConnectHandler
from openpyxl import Workbook
from openpyxl import load_workbook

def read_device_excel( ):

    ip_list = []

    wb1 = load_workbook('/home/netops/venv/cs_lab.xlsx')
    ws1 = wb1.get_sheet_by_name("Sheet1")

    for cow_num in range(2,ws1.max_row+1):

        ipaddr = ws1["a"+str(cow_num)].value
        ip_list.append(ipaddr)

    return ip_list

def get_config(ipaddr):

    session = ConnectHandler(device_type="huawei",
                            ip=ipaddr,
                            username="dev_user",
                            password="dev_password",
                            banner_timeout=300)

    print("connecting to "+ ipaddr)
    print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr))

    # config_data = session.send_command('screen-length 0 temporary')
    # config_data = session.send_command('dis cu | no-more ')
    config_data = session.send_command("dis cu")

    session.disconnect()

    return config_data

def write_config_to_file(config_data,ipaddr):

    now = datetime.now()
    date= "%s-%s-%s"%(now.year,now.month,now.day)
    time_now = "%s-%s"%(now.hour,now.minute)

    #---- Write out configuration information to file
    config_path = '/home/netops/linsy_env/netpro/' +date
    verify_path = os.path.exists(config_path)
    if not verify_path:
        os.makedirs(config_path)

    config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name

    print ('---- Writing configuration: ', config_filename)
    with open( config_filename, "w",encoding='utf-8' ) as config_out:  
        config_out.write( config_data )

    return

def main():
    starting_time = time()   
    ip_list = read_device_excel()
    for ipaddr in ip_list:
        hwconfig = get_config(ipaddr)
        write_config_to_file(hwconfig,ipaddr)
    print ('\n---- End get config threading, elapsed time=', time() - starting_time)

#========================================
# Get config of HUAWEI
#========================================
if __name__ == '__main__':
    main()

执行结果-----------------------------------

5、代码详解

#!/usr/bin/env python
#coding: utf-8

import os
from time import time
from datetime import datetime
from netmiko import ConnectHandler
from openpyxl import Workbook
from openpyxl import load_workbook

def read_device_excel( ):

    ip_list = []

    wb1 = load_workbook('/home/netops/venv/cs_lab.xlsx')
    ws1 = wb1.get_sheet_by_name("Sheet1")

    for cow_num in range(2,ws1.max_row+1):

        ipaddr = ws1["a"+str(cow_num)].value
        ip_list.append(ipaddr)

    return ip_list

def get_config(ipaddr):

    session = ConnectHandler(device_type="huawei",
                            ip=ipaddr,
                            username="dev_user",
                            password="dev_password",
                            banner_timeout=300)

    print("connecting to "+ ipaddr)
    print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr))

    # config_data = session.send_command('screen-length 0 temporary')
    # config_data = session.send_command('dis cu | no-more ')
    config_data = session.send_command("dis cu")

    session.disconnect()

    return config_data

以上内容参考上一个小节银狐DevNet-网络运维Python初篇(三)读取excel信息,批量抓取设备配置,基本没变化。

有个小细节稍微分析一下:

# config_data = session.send_command('screen-length 0 temporary')     
# config_data = session.send_command('dis cu | no-more ')     
config_data = session.send_command("dis cu")

可以看到netmiko抓取设备配置使用了三种方式,最终使用的第三种,前两个又有什么区别呢?我们在设备上show config时回显内容太长经常看到--more--,第一种方式可以使用screen-length 0 temporary命令取消分屏显示(不同厂商命令不同),第二种方式就是个别厂商直接no-more参数(华为CE和Juniper),直接取消分屏显示。为什么我用的第三种方式什么都没加呢?因为netmiko是默认取消分屏的,如果你以后使用paramiko或者其他第三方库,这里需要注意一下。

def write_config_to_file(config_data,ipaddr):

    now = datetime.now()
    date= "%s-%s-%s"%(now.year,now.month,now.day)
    time_now = "%s-%s"%(now.hour,now.minute)

定义配置写入文件的函数,需要2个外参,一个是get_config函数得到的内容,第二个就是设备的IP地址,方便我们给配置文件命名。

同事要设置时间戳,now=datatime.now()就是读取当下时间,年月日时间引入date,几点几分引入time_now。

    config_path = '/home/netops/linsy_env/netpro/' +date
    verify_path = os.path.exists(config_path)
    if not verify_path:
        os.makedirs(config_path)

定义一个本地路径/home/netops/linsy_env/netpro/,并附带时间戳,便于区分是哪天的配置。并做一个判断,假如2021-02-08文件夹已存在,证明今天这个文件夹下已生成过配置文件,那后续的配置文件都存入这个文件夹。如果2021-02-09不存在,那就先创建新的文件夹,在把网络设备的配置文件存入。

    config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name

    print ('---- Writing configuration: ', config_filename)
    with open( config_filename, "w",encoding='utf-8' ) as config_out:  
        config_out.write( config_data )

    return

定义配置文件的名称,注意是在提前定义好的路径下创建新的配置文件,并要附带时间戳,以便我们查看。(也是为了同一天多次备份配置时,配置文件不会因重复而覆盖)

def main():
    starting_time = time()   
    ip_list = read_device_excel()
    for ipaddr in ip_list:
        hwconfig = get_config(ipaddr)
        write_config_to_file(hwconfig,ipaddr)
    print ('\n---- End get config threading, elapsed time=', time() - starting_time)

#========================================
# Get config of HUAWEI
#========================================
if __name__ == '__main__':
    main()

定义主函数,为了看下我们执行所有任务需要的时间,这里加入一下时间统计。(以后使用异步时会看出作用)代码的头部和尾部直接复制代码就好,理解起来很容易,开头记录一下时间(starting_time = time() ),结尾记录一下时间,相减就是代码执行时间( time() - starting_time)。

其余代码和上个小节差不多,需要注意函数write_config_to_file要传入2个参数,一个是get_config函数得到的配置内容,第二个是传入当前设备的IP地址,这样我们生成配置文件时可以根据IP地址命名。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章