网络自动化之python(2):从excel读devices,以可传递给netmiko的数据格式放到list中

网络自动化之python(1)中介绍了以前在公司使用的方法,根据记忆按照模拟器环境将脚本大致还原了回来; 但是从文件中遍历同步处理每台设备的速度很慢,这导致每台设备的光膜快获取大概需要20多秒; 如下方法获取设备信息的速度提升较多; 从一张含有2600台设备的表格中,筛选出自己想要的设备新只需0.26S左右,能大大提升速度,写入到yaml问件中也只需要1.3S左右; 返回的结果见代码中的注释块;

 

# import time
# import json
# import yaml
import xlrd


"""
1、筛选出已上架的设备,
2、筛选出思科、华为、华三、锐捷、F5、惠普的设备;
"""


def excel_to_list():
    data = xlrd.open_workbook(r'.\files\ASSET_test.xlsx')   # 读取表格对象
    sheet1 = data.sheet_by_index(0)  # 取sheet索引值为0的表格
    rows = sheet1.nrows    # 获取行数
    excel_header_list = sheet1.row_values(0)  # 索引(即第一列数据:表头)
    date = []  # 最终的数据列表
    for i in range(1, rows):  # 从第1行开始遍历循环所有行,获取每行的数据
        row_data = sheet1.row_values(i)
        row_data_dict = {}  # 组建每一行数据的字典
        devices_status = row_data[18]
        while devices_status == '已上架':
            devices_type = row_data[28]
            if devices_type == 'F5':
                ios_type = 'F5'
            elif devices_type == '华三':
                ios_type = 'hp_comware'
            elif devices_type == '华为':
                ios_type = 'huawei'
            elif devices_type == '惠普':
                ios_type = 'hp'
            elif devices_type == '锐捷' or devices_type == '星网锐捷':
                ios_type = 'ruijie'
            elif devices_type == '思科':
                ios_type = 'ios'
            else:
                break
            row_data_dict['username'] = 'test'
            row_data_dict['password'] = 'test'
            excel_header_list[21] = 'host'
            excel_header_list[28] = 'device_type'
            row_data_dict[excel_header_list[21]] = row_data[21]
            row_data_dict[excel_header_list[28]] = ios_type
            row_data_dict['port'] = 22
            date.append(row_data_dict)  # 将字典作为单位数据,添加到数据列表中
            break
    return date     # 一台设备信息为一个dict,以dict为元素,组成list

    """
    采用json的格式(str)返回设备信息
    devs_json = json.dumps(date,indent=4)
    return devs_json
    # 将筛选出的设备信息写入yaml文件,抽空学习完nornir后,研究下结合nornir开发使用
    # 写入yaml文件返回数据所有的时间是直接用json格式返回的4倍;
    print(yaml.dump(date))
    with open(r'.\files\hosts.yaml', 'w') as yam:
        yaml.dump(data=date, stream=yam)
        yam.close()
        return yam
    """

# start_time = time.time()
excel_to_list()
# print(f'用时:{time.time()-start_time}s')

 

posted @ 2022-02-17 18:02  段愿仁长九  阅读(187)  评论(0)    收藏  举报