技術メモ

ネットワークエンジニアがpython, perl等々を気楽に使うための覚え書き

python標準のstring.Templateを用いたcisco config作成スクリプト

jinja2もいいけれど...

jinja2の過去記事はこちら


単純な置換だけで完成する差分config程度なら、やはり簡単なのがよい(string.Templateは、perlのheredocくらいの手軽さ)。使い勝手のよさそうな以下の3種類のサンプルスクリプトを作成(Python3.4)。

  • YAMLデータ読み込み版(PyYAML3.11)。
  • CSVデータ読み込み版(Python3.4標準のcsvモジュール)。
  • Excelデータ読み込み版(openpyxl 2.3.0)。

サンプルスクリプトYAML版)

#!/usr/bin/python3
from string import Template
import yaml
import ipaddress

with open('./yml.txt', "r") as f:
    d = yaml.load(f)
with open('./tmpl.txt', "r") as f:
    t = Template(f.read())

for k, v in d.items():
    obj = ipaddress.ip_interface(v['ip'])
    config = t.substitute(
        v,
        host = k,
        ip_addr = obj.with_netmask.replace('/', ' '),
        net_addr = obj.network.with_hostmask.replace('/', ' '),
    )
    with open(k + '.txt', "w") as f:
        f.write(config)

yml.txt(YAMLデータ)

tky-rt01:
    vlan : 2
    ip : 192.168.2.1/24
tky-rt02:
    vlan : 2
    ip : 192.168.2.2/24

サンプルスクリプトCSV版)

#!/usr/bin/python3
from string import Template
import csv
import ipaddress

with open('./data.csv', "r") as f:
    data = [d for d in csv.DictReader(f)]
with open('./tmpl.txt', "r") as f:
    t = Template(f.read())

for d in data:
    obj = ipaddress.ip_interface(d['ip'])
    config = t.substitute(
        d,
        ip_addr = obj.with_netmask.replace('/', ' '),
        net_addr = obj.network.with_hostmask.replace('/', ' '),
    )
    with open(d['host'] + '.txt', "w") as f:
        f.write(config)

data.csvCSVファイル)

host,vlan,ip
tky-rt01,2,192.168.2.1/24
tky-rt02,2,192.168.2.2/24

サンプルスクリプトExcel版)

#!/usr/bin/env python3
from string import Template
from openpyxl import load_workbook
import ipaddress

wb = load_workbook('data.xlsx')
ws = wb.active
data = []
for i in range(1, ws.max_row + 1):
    values = [ws.cell(row = i, column = j).value for j in range(1, ws.max_column + 1)]
    if i == 1:
        keys = values
    else:
        data.append(dict(zip(keys, values)))
with open('./tmpl.txt', "r") as f:
    t = Template(f.read())

for d in data:
    obj = ipaddress.ip_interface(d['ip'])
    config = t.substitute(
        d,
        ip_addr = obj.with_netmask.replace('/', ' '),
        net_addr = obj.network.with_hostmask.replace('/', ' '),
    )
    with open(d['host'] + '.txt', "w") as f:
        f.write(config)

data.xlsx
f:id:mocas:20170207120948j:plain

tmpl.txt(共通テンプレート)

!
! $host config.
!
vlan $vlan
!
interface Vlan$vlan
 ip address $ip_addr
!
router eigrp 1
 network $net_addr
!

tky-rt01.txt(出力結果)

!
! tky-rt01 config.
!
vlan 2
!
interface Vlan2
 ip address 192.168.2.1 255.255.255.0
!
router eigrp 1
 network 192.168.2.0 0.0.0.255
!

tky-rt02.txt(出力結果)

!
! tky-rt02 config.
!
vlan 2
!
interface Vlan2
 ip address 192.168.2.2 255.255.255.0
!
router eigrp 1
 network 192.168.2.0 0.0.0.255
!