コード例 #1
0
def get_credentials(ztp=cvp_vars.getValue(cvp_names.ZTP_STATE)):
    if ztp == 'true':
        user = cvp_vars.getValue(cvp_names.ZTP_USERNAME)
        pwd = cvp_vars.getValue(cvp_names.ZTP_PASSWORD)
    else:
        user = cvp_vars.getValue(cvp_names.CVP_USERNAME)
        pwd = cvp_vars.getValue(cvp_names.CVP_PASSWORD)
    return (user, pwd)
コード例 #2
0
def get_credentials(ztp=GV.getValue(GVN.ZTP_STATE)):
  if ztp == 'true':
    user = GV.getValue(GVN.ZTP_USERNAME)
    pwd = GV.getValue(GVN.ZTP_PASSWORD)
  else:
    user = GV.getValue(GVN.CVP_USERNAME)
    pwd = GV.getValue(GVN.CVP_PASSWORD)
  return (user, pwd)
コード例 #3
0
def modifyACL(acl_name, modify_action, acl_statements, acl_interface_application, apply_interface, remove_interface, apply_directions, remove_directions, device_ips, preview_or_apply):
    username = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME)
    password = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD)
    server = CVP('localhost', username, password)
    server.login()
    if modify_action == "Create/Update" or acl_interface_application is not None:
        CreateOrUpdateACL(acl_name, acl_statements, acl_interface_application, apply_interface, remove_interface, apply_directions, remove_directions, device_ips, preview_or_apply, server)
    elif modify_action == "Delete":
        DeleteACL(acl_name, device_ips, preview_or_apply, server)
    server.logout()
コード例 #4
0
def showAclDetails(device_ips, acl_name):
    output = ""
    user = SSHClientUser(CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME), CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD))
    sshclient = SSHClient(user, device_ips[0])
    cmd = 'sh ip access-lists %s' %(acl_name)
    resp = sshclient.executeCommand( cmd )
    output += resp
    cmd = 'sh ip access-lists %s summary | json' %(acl_name)
    resp = json.loads(sshclient.executeCommand( cmd ) )
    configured_egress_interfaces = []
    configured_ingress_interfaces = []
    for iface in resp["aclList"][0]["configuredEgressIntfs"]:
        configured_egress_interfaces.append(iface["name"])
    for iface in resp["aclList"][0]["configuredIngressIntfs"]:
        configured_ingress_interfaces.append(iface["name"])

    output += "Configured Egress Interfaces\n"
    if len(configured_egress_interfaces) == 0:
        output += "   None\n"
    for iface in configured_egress_interfaces:
        output += "  - {}\n".format(iface)
    output += "\n"
    output += "Configured Ingress Interfaces\n"
    if len(configured_ingress_interfaces) == 0:
        output += "   None\n"
    for iface in configured_ingress_interfaces:
        output += "  - {}\n".format(iface)
    output += "\n"

    print output
コード例 #5
0
def send_commands(commands):
    ip = cvp_vars.getValue(cvp_names.CVP_IP)
    usr, pwd = get_credentials()
    connection_url = 'http://%s:%s@%s/command-api' % (usr, pwd, ip)
    conn = jsonrpclib.Server(connection_url)
    result = conn.runCmds(1, commands)
    return result
コード例 #6
0
def get_leaf_routed_ips(routed_ints):
  user, pwd = get_credentials()
  sw_ip = GV.getValue(GVN.CVP_IP)
  commands = list()
  commands.append('show lldp neighbors detail')
  
  lldp_info = send_command(user, pwd, sw_ip, commands)[0]['lldpNeighbors']
  
  neighbors = dict()
  for rint in routed_ints:
    sw_name = lldp_info[rint]['lldpNeighborInfo'][0]['systemName'].split('.')[0]
    sw_mac = lldp_info[rint]['lldpNeighborInfo'][0]['chassisId'].replace('.','')
    sw_mac = ':'.join(a+b for a,b in zip(sw_mac[::2], sw_mac[1::2]))
    if sw_name not in neighbors.keys():
      neighbors[sw_name] = dict()
    port = lldp_info[rint]['lldpNeighborInfo'][0]['neighborInterfaceInfo']['interfaceId'].replace('"','')
    if port not in neighbors[sw_name].keys():
      neighbors[sw_name][port] = dict()
    neighbors[sw_name][port]['leaf_if'] = rint
    neighbors[sw_name][port]['spine_ip'] = ''
    neighbors[sw_name][port]['leaf_ip'] = ''
    neighbors[sw_name]['spine_mac'] = sw_mac
  
  for device in neighbors.keys():
    commands = list()
    for intf in neighbors[device].keys():
      if 'spine_mac' != intf:
        commands.append('show ip interface {0}'.format(intf))
    
    node = get_net_element(neighbors[device]['spine_mac'])
    _user, _pwd = get_credentials(node['ztpMode'])
    ip_info = send_command(_user, _pwd, node['ipAddress'], commands)
    for ip_intf in ip_info:
      intf = ip_intf['interfaces'].keys()[0]
      ip = ip_intf['interfaces'][intf]['interfaceAddress']['primaryIp']['address']
      neighbors[device][intf]['spine_ip'] = ip
      octect = ip.split('.')
      fourth = int(octect[3]) + 1
      leaf_ip = '{0}.{1}.{2}.{3}'.format(octect[0], octect[1], octect[2], fourth)
      neighbors[device][intf]['leaf_ip'] = leaf_ip
    
  routed_info = list()
  for device in neighbors.keys():
    for intf in neighbors[device].keys():
      if 'spine_mac' != intf:
        leaf_if = neighbors[device][intf]['leaf_if']
        leaf_ip = neighbors[device][intf]['leaf_ip']
        spine_ip = neighbors[device][intf]['spine_ip']
        routed_info.append((leaf_if, device, intf.replace('/','_'), leaf_ip, spine_ip))

  return routed_info
コード例 #7
0
def main():
    if CVPGlobalVariables.getValue(
            GlobalVariableNames.ZTP_STATE
    ) == 'true':  # If device in ztp state, continue.
        device_ip = CVPGlobalVariables.getValue(
            GlobalVariableNames.CVP_IP)  # Get Device IP
        device_user = CVPGlobalVariables.getValue(
            GlobalVariableNames.ZTP_USERNAME)  # Get CVP temp username for ZTP.
        device_pass = CVPGlobalVariables.getValue(
            GlobalVariableNames.ZTP_PASSWORD)  # Get CVP temp password for ZTP.
        device = Device(
            device_ip, device_user,
            device_pass)  # Create eAPI session to device via Device library.
        currentVersion = device.runCmds(
            ['enable', 'show version'])[1]['response'][
                'version']  # Get currently installed version of device
        if currentVersion == image_to_downgrade:  # If device version is same as image_to_downgrade var, try to downgrade it.
            if cvp_image == 'undefined':
                EOSImage = get_undefined_image()
            else:
                EOSImage = specific_image
            try:
                print 'Uploading EOS version ' + EOSImage + ' to device ' + device_ip
                device.runCmds(['enable', cvpInstallImage + EOSImage])
                print 'Checking Boot Vars on device ' + device_ip
                bootvar = device.runCmds(['enable', 'show boot'
                                          ])[1]['response']['softwareImage']
                if bootvar.endswith(EOSImage):
                    print 'Boot Var matches installed image. Rebooting now.'
                    try:
                        device.runCmds(['enable', 'reload now'])
                    except:
                        pass
            except:
                pass
    else:
        pass
コード例 #8
0
def showAclNames(device_ips):
    user = SSHClientUser(CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME), CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD))
    sshclient = SSHClient(user, device_ips[0])
    cmd = 'sh ip access-lists | json'
    resp = sshclient.executeCommand( cmd )
    resp_json = json.loads(resp)
    acl_names = []
    for acl in  resp_json["aclList"]:
        if acl["dynamic"] == False and acl["readonly"] == False:
            acl_names.append( acl["name"] )
    
    if len(acl_names) == 0:
        print "No configured ACLs found"
    for name in acl_names:
        print name
コード例 #9
0
def sendCmd(commands):
    ztp = cvpGV.getValue(GVN.ZTP_STATE)
    hostip = cvpGV.getValue(GVN.CVP_IP)
    if ztp == 'true':
        user = cvpGV.getValue(GVN.ZTP_USERNAME)
        passwd = cvpGV.getValue(GVN.ZTP_PASSWORD)
    else:
        user = cvpGV.getValue(GVN.CVP_USERNAME)
        passwd = cvpGV.getValue(GVN.CVP_PASSWORD)

    url = "https://%s:%s@%s/command-api" % (user, passwd, hostip)
    switch = jsonrpclib.Server(url)
    response = switch.runCmds(1, commands)[0]
    return response
コード例 #10
0
def get_routed_info(interfaces):
    routed_info = list()
    user, pwd = get_credentials()
    sw_ip = cvp_vars.getValue(cvp_names.CVP_IP)
    commands = ['show lldp neighbors detail']
    lldp_info = send_command(user, pwd, sw_ip, commands)[0]['lldpNeighbors']

    for _int in interfaces:
        lldp_neigh = lldp_info[_int]['lldpNeighborInfo'][0]
        neigh_mac = lldp_neigh['chassisId'].replace('.', '')
        neigh_mac = ':'.join(a + b
                             for a, b in zip(neigh_mac[::2], neigh_mac[1::2]))
        neigh_int = lldp_neigh['neighborInterfaceInfo']['interfaceId'].replace(
            '"', '')

        node = get_net_element(neigh_mac)
        _user, _pwd = get_credentials(node['ztpMode'])
        _commands = ['show ip interface %s' % neigh_int]
        int_info = send_command(_user, _pwd, node['ipAddress'],
                                _commands)[0]['interfaces']
        cidr = int_info[neigh_int]['interfaceAddress']['primaryIp']['maskLen']
        neigh_ip = int_info[neigh_int]['interfaceAddress']['primaryIp'][
            'address']
        ip_info = neigh_ip.split('.')
        local_ip = '%s.%s' % ('.'.join(ip_info[:3]), str(int(ip_info[-1]) + 1))

        entry = dict()
        entry['localInt'] = _int
        entry['localIp'] = local_ip
        entry['neighMac'] = neigh_mac
        entry['neighInt'] = neigh_int
        entry['neighIp'] = neigh_ip
        entry['cidr'] = cidr
        entry['systemName'] = node['fqdn'].split('.')[0]

        routed_info.append(entry)

    return routed_info
コード例 #11
0
def get_interfaces():
    ## If interfaces need to be excluded, add to exempt_ints
    exempt_ints = list()
    exempt_ints.append('Management0')
    exempt_ints.append('Management1')
    exempt_ints.append('Management1/1')
    exempt_ints.append('Management1/2')
    exempt_ints.append('Management2/1')
    exempt_ints.append('Management2/2')

    interfaces = list()
    user, pwd = get_credentials()
    sw_ip = cvp_vars.getValue(cvp_names.CVP_IP)
    commands = ['show interfaces status']
    int_status = send_command(user, pwd, sw_ip,
                              commands)[0]['interfaceStatuses']

    for key in int_status.keys():
        if key in exempt_ints:
            continue
        else:
            interfaces.append(key)

    return sorted(interfaces)
コード例 #12
0
import yaml
import requests
import json
from cvplibrary import CVPGlobalVariables, GlobalVariableNames
from cvplibrary import Device

#Revision 0.4

device_ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
dev_user = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME)
dev_pass = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD)

def authenticate():
  #Send username and password via API and get session ID in cookies in order to use for future API calls.
  
  #Login API Url
  authUrl = "https://localhost/web/login/authenticate.do"
  
  #Create JSON object with username and password.
  authPayload = '''{
    "userId": \"%s\",
    "password": \"%s\"
    }''' % (dev_user, dev_pass)
    
  #Establish connection headers                  
  headers = {
      'Content-Type': "application/json",
      'cache-control': "no-cache",
      }
  
  #Perform API call for authentication and log response as a variable.
コード例 #13
0
def build_allocations(session, pools):
    allocs = get_network_allocations(session, 'overlay', 'ipv4')['data']
    for item in allocs:
        desc = item['description']
        parent = item['parentsubnet']
        if desc in pools[parent]['allocations'].keys():
            continue
        else:
            pools[parent]['allocations'][desc] = item

    return pools


session = get_session_id()
sys_mac = cvp_vars.getValue(cvp_names.CVP_MAC)
systems = get_systems(session)
sys_hostname = systems[sys_mac]
asns = build_asns(session)
sys_asn = asns[sys_hostname]
pools = build_pools(session, 'overlay-ipv4')
pools = build_allocations(session, pools)

vrfs = set()
vxlan_vlans = dict()
flood_list = set()
vtep = netaddr.IPNetwork(pools['%s_vtep' % sys_hostname]['range'])
varp_vtep = netaddr.IPNetwork(pools['varp_vtep']['range'])

for key in pools.keys():
    if 'group' in pools[key].keys() and 'vlan' in pools[key].keys():
コード例 #14
0
try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context
#
# Get all data from Form
spine1_port_num = Form.getFieldById('spine1_port_num').getValue()
spine2_port_num = Form.getFieldById('spine2_port_num').getValue()
spine3_port_num = Form.getFieldById('spine3_port_num').getValue()

ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
myCVPuser = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME)
myCVPpasswd = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD)

#
# Username/password/protocol for eAPI access to switches
#

EAPI_USERNAME = myCVPuser
EAPI_PASSWORD = myCVPpasswd
EAPI_METHOD = 'https'

#
# Via eAPI call get detect unique loopback ip address use to derive fabric interfaces
##!!Changing "unique_loopback_ip to call loopback0 for Jasons Lab!!"
switch = Server('%s://%s:%s@%s/command-api' %
コード例 #15
0
from netaddr import *
import json
import yaml
import re
from jinja2 import Template
import requests
from cvplibrary import RestClient
import ssl
from cvplibrary import CVPGlobalVariables, GlobalVariableNames

device_sn = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_SERIAL)

# Ignore untrusted certificate for eAPI call.
ssl._create_default_https_context = ssl._create_unverified_context

### CVP REST - Puts Configlets in CVP.
cvpserver = 'https://localhost:443'
rest_get_configlet_by_name = '/cvpservice/configlet/getConfigletByName.do?name='

### YAML Locationrest_get_configlet_by_name = '/cvpservice/configlet/getConfigletByName.do?name='

# YAML can either be stored in CVP directly or off-box on an http url.
yaml_location = 'cvp'  # 'http' | 'cvp'

## http storage. Define the full requests url.
if yaml_location == 'http':
    yaml_http = requests.get(
        'http://gitlab.example.com/root/YamlBuilder/raw/master/example.yaml')
    yamlfile = yaml_http.text
## CVP Storage - define yaml_configlet as the name of the configlet.
if yaml_location == 'cvp':
コード例 #16
0
import urllib3
import json
import yaml
import jinja2
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

###################Define Global Variables###################
username = '******'
password = '******'
cvp_server = '10.0.0.14'
api_headers = {
    'Content-Type': "application/json",
    'cache-control': "no-cache",
}
api_root = 'https://{0}/web'.format(cvp_server)
device_ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
#############################################################


def authenticate():

    url_path = api_root + '/login/authenticate.do'
    payload = {"userId": username, "password": password}

    response = requests.request('POST',
                                url_path,
                                data=json.dumps(payload),
                                headers=api_headers,
                                verify=False)
    return (response.cookies)
コード例 #17
0
import jsonrpclib
from cvplibrary import CVPGlobalVariables, GlobalVariableNames

ztp = CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_STATE)
ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)

if ztp == 'true':
    user = CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_USERNAME)
    passwd = CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_PASSWORD)
else:
    user = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME)
    passwd = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD)


def get_hostname():
    url = "https://%s:%s@%s/command-api" % (user, passwd, ip)
    ss = jsonrpclib.Server(url)
    show_hostname = ss.runCmds(1, ["enable", {"cmd": "show hostname"}])[1]
    hostname = show_hostname['hostname']
    return hostname


def create_routes(hostname):
    number = hostname[-1:]
    if hostname.startswith("leaf"):
        switch_type = "10"
    elif hostname.startswith("spine"):
        switch_type = "20"
    for x in range(100, 200):
        print "int lo%d" % (x)
import ssl

try:
  _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
  pass
else:
# Handle target environment that doesn't support HTTPS verification
  ssl._create_default_https_context = _create_unverified_https_context

ssl._create_default_https_context = ssl._create_unverified_context
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()

cvp_username = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME)
cvp_password = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD)

clnt = CvpClient()
clnt.connect(['localhost'], cvp_username, cvp_password)
configlet_name = "cvp_1_site_users_pwd_config"

output = clnt.api.get_configlet_by_name(name = configlet_name)
config = output["config"]
key = output["key"]

new_config = ""

for line in config.splitlines():
  if "secret" in line or "enable" in line:
    words = line.split()
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
"""Multicast Auto Reconcile Configlet Builder
This Python code must be used as configlet builder on CVP
It helps to reconcile the config produced by M&E controller (multicast routes) automatically.
This builder can be triggered before executing the change by trigger-mcast-reconcile.py
"""

__author__ = 'Petr Ankudinov'

from cvplibrary import CVPGlobalVariables, GlobalVariableNames, Device
from time import time

# find device IP
device_ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
device_serial = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_SERIAL)
# find username and password
ztp = CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_STATE)
if ztp == 'true':
    user = CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_USERNAME)
    passwd = CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_PASSWORD)
else:
    user = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME)
    passwd = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD)

device = Device(device_ip, username=user, password=passwd)
cmdList = ['enable', 'show running-config']
# get `router multicast` config section
mcast_config = device.runCmds(cmdList)[1]['response']['cmds'][
    'router multicast']['cmds']['ipv4']['cmds'].keys()
コード例 #20
0
from cvplibrary import Form
from cvplibrary import CVPGlobalVariables, GlobalVariableNames
from cvplibrary import RestClient
import sys


def netid_to_serialnum(net_id):
    query = 'http://localhost:8080/web/provisioning/getNetElementById.do?netElementId=%s' % mac
    client = RestClient(query, 'GET')
    if client.connect():
        dev_info = json.loads(client.getResponse())
        return dev_info['serialNumber']
    return None


mac = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_MAC)
serialnum = netid_to_serialnum(mac)

with open('mgmt_applicator.csv', 'rb') as f:
    reader = csv.reader(f)
    sertohost = list(reader)
# Capturing the hostname of the device
for items in sertohost:
    if items[0] == serialnum and items[1].startswith(('as', 'sw')):
        hostname = items[1]

with open('bgpfile.csv', 'rb') as f:
    reader = csv.reader(f)
    bgpinfo = list(reader)
# Capturing hostnames of all BGP hosts here
bgp_col1 = set()
コード例 #21
0
import jsonrpclib
import json
import requests

# Set Form Variables and static
lo0 = Form.getFieldById('lo0').getValue()
lo0 = netaddr.IPNetwork('%s/32' % lo0)
lo1 = Form.getFieldById('lo1').getValue()
lo1 = netaddr.IPNetwork('%s/32' % lo1)
lo1_sec = Form.getFieldById('lo1_sec').getValue()
lo1_sec = netaddr.IPNetwork('%s/32' % lo1_sec)
mlag_subnet = Form.getFieldById('mlag_subnet').getValue()
mlag_subnet = netaddr.IPNetwork(mlag_subnet)
leaf_asn = Form.getFieldById('leaf_asn').getValue()
spine_asn = Form.getFieldById('spine_asn').getValue()
mac = cvp_vars.getValue(cvp_names.CVP_MAC)
routed_ints = list()
routed_ints.append('Ethernet2')
routed_ints.append('Ethernet3')
mlag_peer_ints = list()
mlag_peer_ints.append('Ethernet1')
mlag_ints = list()
mlag_ints.append('Ethernet4')


# Functions to build leaf configuration
def get_net_element(system_mac):
    url = 'http://localhost:8080/cvpservice/provisioning/getNetElementById.do?netElementId=%s' % system_mac
    client = RestClient(url, 'GET')
    client.connect()
    node_info = json.loads(client.getResponse())
コード例 #22
0
def main():
    device_ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP) # Get Device IP
    device = Device(device_ip,device_user,device_pass) # Create eAPI session to device via Device library.
    reboot = device.runCmds(['enable','write','reload now']) # Get currently installed version of device
コード例 #23
0
ファイル: vlan_vrf_ip.py プロジェクト: sergeyd16/good-ways
from cvplibrary import Form
from jsonrpclib import Server
from cvplibrary import CVPGlobalVariables, GlobalVariableNames

#fetching the management ip of the current device
device_ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
#fetching the username for the current device
username = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_USERNAME)
#fetching the password for the current device
password = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_PASSWORD)

#fetching the variables from the form
intvlan_var = Form.getFieldById("field_1").getValue()
vrf_var = Form.getFieldById("field_2").getValue()
ipaddrv = Form.getFieldById("field_3").getValue()

print "vrf definition " + vrf_var

print "vlan " + intvlan_var
print "interface vlan " + intvlan_var
print "mtu 9000"
print "no autostate"
print "vrf forwarding " + vrf_var
print "ip address virtual " + ipaddrv + "/24"

print "interface Vxlan1"
print "vxlan vlan " + intvlan_var + " vni " + intvlan_var

#connecting to the switch
switch = Server('https://%s:%s@%s/command-api' %
                (username, password, device_ip))
コード例 #24
0
configletPrefix = 'techspt_'
commandList = [
    'show ip bgp summary', 'show ip arp', 'show bgp evpn summary',
    'show mac address-table', 'show tech-support'
]
overwrite_configlets = True  # Set to False if you want to protect configlets from overwrite.

# Ignore untrusted certificate for eAPI call.
ssl._create_default_https_context = ssl._create_unverified_context

### CVP REST - Puts Configlets in CVP.
cvpserver = 'https://*****:*****@%s/command-api" % (user, passwd, device_ip)
ss = jsonrpclib.Server(url)

HTTP_TIMEOUT = 120


def check_configlet_exists(configlet_name):
    client = RestClient(
        cvpserver + rest_get_configlet_by_name + configlet_name, 'GET')
    if client.connect():
        output = json.loads(client.getResponse())
        if 'errorCode' in output:
コード例 #25
0
import json
import re
from cvplibrary.auditlogger import alog
from cvplibrary import Device, CVPGlobalVariables, GlobalVariableNames
ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
serial = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_SERIAL)
session_id = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_SESSION_ID)
scriptArgs = CVPGlobalVariables.getValue(GlobalVariableNames.SCRIPT_ARGS)
alog("Remove all old EOSs from /mnt/flash")

switch = Device(ip)
# Get current boot image
cmdOut = switch.runCmds(["show boot"])
eosBootImageFull = cmdOut[0]["response"]["softwareImage"]
eosBootImage = eosBootImageFull.split("/")[1]

cmdOut = switch.runCmds(["dir flash:EOS*"])
eosListTxt = cmdOut[0]["response"]["messages"][0]
eosList = re.findall(r'EOS.*\.swi', eosListTxt)

for eos in eosList:
    if eos != eosBootImage:
        cmd = "delete flash:" + eos
        cmdOut = switch.runCmds([cmd])
コード例 #26
0
"""
This script is used to create BGP configurations within the L3 leaf and spine topology.
"""

import sys
sys.path.append('/usr/lib64/python2.7/site-packages/')
import yaml
from cvplibrary import CVPGlobalVariables as cvpGV
from cvplibrary import GlobalVariableNames as GVN

#Variable declarations
yFile = 'hostvars/dc1.yml'

smac = cvpGV.getValue(GVN.CVP_MAC)

yaml_file = open(yFile)
infoY = yaml.load(yaml_file)
yaml_file.close()

shost = infoY['device'][smac]

#Grabbing sections of the YAML file
curINT = infoY['configurations'][shost]['interfaces']
curBGP = infoY['configurations'][shost]['BGP']
lloopINT = None

try:
    lloopINT = curINT['loopback']['Loopback0']['ip']
    lloopINTN = '%s/%s' % (lloopINT, curINT['loopback']['Loopback0']['cidr'])
except:
    pass
コード例 #27
0
from cvplibrary import CVPGlobalVariables, GlobalVariableNames, Device

vlanRangeStart = '4000'
vlanRangeEnd = '4094'

# Check if Device is in ZTP Mode:
if CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_STATE) == 'true':
    device_ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
    device_user = CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_USERNAME)
    device_pass =CVPGlobalVariables.getValue(GlobalVariableNames.ZTP_PASSWORD)
    device = Device(device_ip,device_user,device_pass)
    iflist = device.runCmds(['enable','show interfaces status'])[1]['response']
    vlanOrder = device.runCmds(['enable', 'configure', 'vlan internal order ascending range '+vlanRangeStart+' '+vlanRangeEnd])
    for item in iflist['interfaceStatuses'].keys():
       if item.startswith('Ethernet'):
           device.runCmds(['enable','configure','interface '+item,'shutdown'])
           device.runCmds(['enable','configure','interface '+item,'no shutdown'])
else:
    pass
#end device set-up.
コード例 #28
0
test = False
if not RequestSession.getSessionId():
   test = True

# Log message handling
def outMsg(test,msgTxt):
    """ Output log messages to stdout if testing
      or CVP CC log if running in CVP
    """
    if test:
        print(msgTxt)
    else:
        alog(msgTxt)

# Create Script variables
scriptArgs = CVPGlobalVariables.getValue( GlobalVariableNames.SCRIPT_ARGS)
scriptArgs['deviceList']=re.split(',',scriptArgs['deviceList'])

# Internal Variables
host_port = 22
passed = 0
failed = 0

# Write entry to Log
outMsg(test, "page_check - check Web Page connectivity")

# Intialise SSH
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Start ping tests from devices in deviceList
コード例 #29
0
ファイル: cvp-L3-intfs.py プロジェクト: networkRob/cvp-l3ls
"""
This script is used to create L3 interfaces for ethernet, svi's, and loopback interfaces.
"""

import sys
sys.path.append('/usr/lib64/python2.7/site-packages/')
import yaml
from cvplibrary import CVPGlobalVariables as cvpGV
from cvplibrary import GlobalVariableNames as GVN

#Variable declarations
yFile = 'hostvars/dc1.yml'
virtual_MAC = '00:1c:73:00:00:99'

select_mac = cvpGV.getValue(GVN.CVP_MAC)
sIP = cvpGV.getValue(GVN.CVP_IP)

yaml_file = open(yFile)
info_yaml = yaml.load(yaml_file)
yaml_file.close()

shost = info_yaml['device'][select_mac]

#Grabbing sections of the YAML file
device_interfaces = info_yaml['configurations'][shost]['interfaces']
list_device_interfaces = []
#dict_loopback_interfaces = {}
list_svi_interfaces = []
VARP = False

#L3 ethernet interfaces
コード例 #30
0
   alog(string) - alog function writes the string to the audit logs tagged with the specific change control
   calling the script

Smaple yaml file
   name : check_switchType
   args:
      switchType : vEOS

"""
# Import required Librarys
import json
from cvplibrary.auditlogger import alog  # CVP auit log function
from cvplibrary import Device, CVPGlobalVariables, GlobalVariableNames  # CVP Variables

# Create Script variables
ipAddress = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
scriptArgs = CVPGlobalVariables.getValue(GlobalVariableNames.SCRIPT_ARGS)

# Write entry to Log
alog("running show version from script to check switch type")
# Connect to Device specified in Change Control
switch = Device(ipAddress)
# Run show commands on switch
cmdOut = switch.runCmds(["show version", "show hostname"])
# Check if the switch type is correct
if str(scriptArgs['switchType']) not in cmdOut[0]["response"]["modelName"]:
    logTxt = "WARNING: switch %s is not a %s it is a %s" % (
        cmdOut[1]["response"]["hostname"], scriptArgs['switchType'],
        cmdOut[0]["response"]["modelName"])
    alog(logTxt)
    assert (False)