Friday, September 16, 2016

script to auto generate and configure bgp for core-network

core-network can configure ospf or ospfv3 automatically, but it does not configure bgp automatically, and below is the script to do the task

#!/usr/bin/python
import pexpect
import sys
import re
import ipaddress
import xmltodict

with open('session-deployed.xml') as fd:
    doc = xmltodict.parse(fd.read())

ar = doc['scenario']['router']
drouter = {}
for i in ar:
    routern =  i['@id']
    asn = re.search(r"\d+",routern).group(0)
    drouter[routern] = {}
    drouter[routern]['address'] = []
    drouter[routern]['asn'] = asn
    if type(i['interface']) == list:
        for j in i['interface']:
            for k in j['address']:
                if k['@type'] =='IPv4':
                    address = k["#text"].split("/")[0]
                    drouter[address] = {}
                    drouter[address]['name'] = routern
                    drouter[address]['asn'] = asn
                    drouter[routern]['address'].append(address)
    else:
         for k in i['interface']['address']:
             if k['@type'] =='IPv4':
                    address = k["#text"].split("/")[0]
                    drouter[address] = {}
                    drouter[address]['name'] = routern
                    drouter[address]['asn'] = asn
                    drouter[routern]['address'].append(address)

def generateconfig(routern):
    l1 = "router bgp " + drouter[routern]['asn'] + "\n"
    l2 = "network 10.0.0.0/8\n"
    lb = ""
    for i in drouter[routern]['address']:
        addr = ipaddress.IPv4Interface(i.encode('utf-8') + u"/24")
        for i in range(1,6):
            naddr = addr.network.network_address + i
            if addr.ip != naddr:
                naddr = str(naddr)
                if naddr in drouter.keys():

                    rtn = drouter[naddr]['name']
                    rtas = drouter[naddr]['asn']
                    l3 = "neighbor "+ rtn +" peer-group\n"
                    l4 = "neighbor "+ rtn +" remote-as "+ rtas +"\n"
                    l5 = "neighbor "+ rtn +" soft-reconfiguration inbound\n"
                    l6 = "neighbor "+ naddr +" peer-group "+rtn+"\n"
                    lb += l3 + l4 + l5 +l6
    finl = l1 + l2 + lb
    return finl


rnf = sys.argv[1]
rnl = rnf.split("/")
rn = rnl[len(rnl) -1]
routerconf = generateconfig(rnf)

print routerconf
child = pexpect.spawn('vcmd -c ' + rnf)

child.expect(".*#")
child.sendline ('VTYSH_PAGER=more vtysh')

child.expect(rn+"#")


child.sendline("conf t")
child.expect("conf")
allint = child.before
allintl = allint.split("Interface")
child.send(routerconf)
child.sendline("exit")
child.sendline("exit")
child.sendline("exit")



1- script usage
go to core tmp directory, usually reside in /tmp/core.pid (ex- /tmp/pycore.42295)

and execute the script with router name you want to configure
$ auto-configure-core-network-bgp.py n5

- snapshot of script when execute.


No comments:

Post a Comment