根据配置模板,生成设备配置

功能

从excel读入配置信息,根据预定义配置模板生成配置。功能虽然简单,但是要考虑通用性,配置模板改变时,不需要修改代码。

配置信息表格

第一行为设备名称,程序将以设备名称为文件名,写入设备配置。其余部分可以
在这里插入图片描述

配置文件包含配置模板信息

[intf_desc]
sheet = interface
intf_tempalte= template/inf_template.txt

template/inf_template.txt 内容如下:

interface {0[0]}
  description {0[1]} {0[2]} {0[3]} {0[4]} {0[5]}
exit  

excel读模块

class ExcelHandler:
    def __init__(self, file):
        self.file = file
    def sheet_read(self, sheet):
        xls_data_list = []
        xls = xlrd.open_workbook(self.file)
        table = xls.sheet_by_name(sheet)
        nrows = table.nrows
        for row_index in range(1,nrows):
            xls_data_list.append(table.row_values(row_index))
        return xls_data_list

配置生成模块和主函数

import configparser
from handler.excel_handler import ExcelHandler
config = configparser.ConfigParser()
config.read("etc/config.ini")
intf_des = config["intf_desc"]["desc"]
sheet = config["intf_desc"]["sheet"]
inf_template = config["intf_desc"]["intf_tempalte"]

class ConfigGenerate:
    def __init__(self):
        pass

    @staticmethod
    def replace_generate(data, template, file_name):
        """
        :param data: configuration information
        :param template: config template
        :param file_name: destination file
        :return:
        """

        intf_config = template.format(data[1:7])
        with open(file_name, 'a') as file:
            file.write(intf_config+'\n')


if __name__ == "__main__":
    config = ConfigGenerate()
    excel_inst = ExcelHandler("config_inform.xlsx")
    intf_data = excel_inst.sheet_read("interface")
    with open(inf_template, 'r') as f:
        intf_template = f.read()
    for row in intf_data:
        config.replace_generate(row, intf_template, row[0])

程序运行后,会生成以pe1,pe2,pe3,pe4,pe5,pe6 的文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值