Beispiel #1
0
def getDeviceRTRID():
  #Get device name to determine Device BGP AS
  cmdList = ['show ip bgp summary']
  device = Device(device_ip,dev_user,dev_pass)

  dict_resp = device.runCmds(cmdList)
  device_rtrid = dict_resp[0]['response']['vrfs']['default']['routerId']
  device_as = dict_resp[0]['response']['vrfs']['default']['asn']
  return device_rtrid, device_as
Beispiel #2
0
def getDeviceNAMEID():
  #Get device name to determine SVI IP
  cmdList = ['show hostname']
  device = Device(device_ip,dev_user,dev_pass)

  dict_resp = device.runCmds(cmdList)
  device_hostname = dict_resp[0]['response']['hostname']
  svi_id = "2"
  if device_hostname.endswith('2'):
    svi_id = "3"
  return device_hostname, svi_id
Beispiel #3
0
def get_device_info():
    #Get information for loopback0 and bgp
    cmd_list = ['enable', 'show interfaces loopback0', 'show ip bgp']
    device = Device(device_ip, username, password)
    device_info = device.runCmds(cmd_list)

    #Get Loopback IP from dictionary
    loopback_ip = device_info[1]['response']['interfaces']['Loopback0'][
        'interfaceAddress'][0]['primaryIp']['address']

    #Get BGP AS from Dictionary
    bgp_as = device_info[2]['response']['vrfs']['default']['asn']

    return (loopback_ip, bgp_as)
def get_lldp_neighbors():
    #Get lldp neighbors
    lldp_interface_dict = {}
    cmd_list = ['enable', 'show lldp neighbors detail']
    device = Device(device_ip, username, password)
    lldp_neighbors = device.runCmds(cmd_list)[1]['response']['lldpNeighbors']

    for interface in lldp_neighbors:
        if interface != 'Management1':
            neighbor_info = lldp_neighbors[interface]['lldpNeighborInfo']
            for neighbor in neighbor_info:
                neighbor_ip = neighbor['managementAddresses'][0]['address']
                lldp_interface_dict[interface] = neighbor_ip

    return (lldp_interface_dict)
def main():
    tempconfiglet = []
    device = Device(device_ip)
    hostname = device.runCmds(['show hostname'], )[0]['response']['hostname']
    for command in commandList:
        tempconfiglet.append('============' + command + '============')
        # Note: TXT Format not supported til 2019.1.0+ for Device() library.
        try:
            output = ss.runCmds(1, ['enable', command], 'text')[1]['output']
        except:
            output = 'Error: command not supported'
        tempconfiglet.append(output)
    configletName = configletPrefix + hostname
    configletBody = '\n'.join(tempconfiglet)
    configletExists = check_configlet_exists(configletName)
    if configletExists:
        configletKey = configletExists
        update_configlet(configletBody, configletName, configletKey)
    else:
        add_configlet(configletBody, configletName)
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
Beispiel #7
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])
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
Beispiel #9
0
from cvplibrary import CVPGlobalVariables, GlobalVariableNames
from cvplibrary import Device

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

cmdList = ['show hostname']
device = Device(device_ip,dev_user,dev_pass)

dict_resp = device.runCmds(cmdList)
device_hostname = dict_resp[0]['response']['hostname']
mlag_ip = "192.0.0.1/24"
mlag_ip_peer = "192.0.0.2"
domain_id = "1000"
peer_name = device_hostname[:-1] + "B"

if device_hostname.endswith('B'):
  mlag_ip = "192.0.0.2/24"
  mlag_ip_peer = "192.0.0.1"
  peer_name = device_hostname[:-1] + "A"

print "vlan 4094"
print "name MLAGPEER"
print "trunk group MLAGPEER"
print "!"
print "no spanning-tree vlan 4094"
print "!"
print "interface Vlan4094"
print "description MLAG PEER SYNC"
print "no autostate"
Beispiel #10
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.
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()
# re-build multicast config from the device running config
print('router multicast')
print('   ipv4')
for line in mcast_config:
    print(' ' * 6 + line)
    outMsg(test, "device_ping - ping device set to EOS")
else:
    outMsg(test, "device_ping - ping device INVALID")
    if not test:
        raise UserWarning("device_ping: Failed")

# Start ping tests from devices in deviceList
for device_ip in scriptArgs['deviceList']:
    outMsg(test, "device_ping: Connecting to %s" % device_ip)
    if scriptArgs['hostType'] == "nix":
        ssh.connect(device_ip,
                    port=host_port,
                    username=scriptArgs['username'],
                    password=scriptArgs['password'])
    else:
        switch = Device(device_ip)
    for target in scriptArgs['targetList']:
        if scriptArgs['hostType'] == "nix":
            stdin, stdout, stderr = ssh.exec_command(
                'ping -c %s -w %s %s' %
                (scriptArgs['pingCount'], scriptArgs['timeout'], target))
            output = stdout.readlines()
        else:
            #output = switch.runCmds(["enable", "bash timeout 20 ping -c %s -w %s %s" % (scriptArgs['pingCount'],
            #                                                                            scriptArgs['timeout'], target)])[1]["response"]
            tempOutput = switch.runCmds([
                "enable",
                "cli vrf %s" % scriptArgs['vrf'],
                "ping %s" % target
            ])
            outMsg(test, "device_ping: eAPI Response %s" % tempOutput)
Beispiel #13
0
import json
import time
from cvplibrary.auditlogger import alog
from cvplibrary import Device, CVPGlobalVariables, GlobalVariableNames

ip = CVPGlobalVariables.getValue(GlobalVariableNames.CVP_IP)
scriptArgs = CVPGlobalVariables.getValue(GlobalVariableNames.SCRIPT_ARGS)
alog("running shut_host_links from script")
d = Device(ip)
Output = d.runCmds(
    ["enable", "configure", "maintenance", "unit shut-host-links", "quiesce"])
maintmode = False
time.sleep(5)
numoftries = 0
while (maintmode is False and numoftries < 5):
    Output = d.runCmds(["show maintenance"])
    if Output[0]["response"]["units"]["shut-host-links"][
            "adminState"] == "underMaintenance":
        maintmode = True
        alog("Under maintenance")
    else:
        alog("Entering maintenance")
        time.sleep(30)
    numoftries += 1
   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)
else:
    logTxt = "SUCCESS: switch %s is a %s" % (
        cmdOut[1]["response"]["hostname"], cmdOut[0]["response"]["modelName"])
    alog(logTxt)
Beispiel #15
0
from sys import path
path.append('/usr/lib64/python2.7/site-packages/')
import yaml
from cvplibrary import CVPGlobalVariables, GlobalVariableNames, Device

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)

ss = Device(ip,user,passwd)

def get_hostname():
    show_hostname = ss.runCmds(["enable", {"cmd": "show hostname"}])[1]
    hostname = show_hostname['response']['hostname']
    return hostname

def get_bgpasn():
    show_ip_bgp_summary = ss.runCmds(["enable", {"cmd": "show ip bgp summary"}])[1]
    asn = show_ip_bgp_summary['response']['vrfs']['default']['asn']
    return asn

def create_routes(hostname):
    number = hostname[-1:]
    if hostname.startswith("leaf"):
        switch_type = "10"