Ejemplo n.º 1
0
def main():
    '''
    Add/remove vlans from Arista switch in an idempotent manner
    '''

    arista_dict = dict(
        hostname='10.10.10.10',
        port=8543,
        username='******',
        password='******',
    )

    eapi_conn = eapilib.create_connection(**arista_dict)

    # Argument parsing
    parser = argparse.ArgumentParser(
        description="Idempotent addition/removal of VLAN to Arista switch")
    parser.add_argument("vlan_id",
                        help="VLAN number to create or remove",
                        action="store",
                        type=int)
    parser.add_argument("--name",
                        help="Specify VLAN name",
                        action="store",
                        dest="vlan_name",
                        type=str)
    parser.add_argument("--remove",
                        help="Remove the given VLAN ID",
                        action="store_true")

    cli_args = parser.parse_args()
    vlan_id = cli_args.vlan_id
    remove = cli_args.remove
    vlan_name = cli_args.vlan_name

    # Check if VLAN already exists
    check_vlan = check_vlan_exists(eapi_conn, vlan_id)

    # check if action is remove or add
    if remove:
        if check_vlan:
            print "VLAN exists, removing it"
            command_str = 'no vlan {}'.format(vlan_id)
            eapi_conn.config([command_str])
        else:
            print "VLAN does not exist, no action required"

    else:

        if check_vlan:
            if vlan_name is not None and check_vlan != vlan_name:
                print "VLAN already exists, setting VLAN name"
                configure_vlan(eapi_conn, vlan_id, vlan_name)
            else:
                print "VLAN already exists, no action required"

        else:
            print "Adding VLAN including vlan_name (if present)"
            configure_vlan(eapi_conn, vlan_id, vlan_name)
Ejemplo n.º 2
0
def main():
    '''
    Add/remove vlans from Arista switch in an idempotent manner
    '''

    arista_dict = dict(
        hostname='10.10.10.10',
        port=8243,
        username='******',
        password='******'
    )

    eapi_conn = eapilib.create_connection(**arista_dict)

    # Argument parsing
    parser = argparse.ArgumentParser(
        description="Idempotent addition/removal of VLAN to Arista switch"
    )
    parser.add_argument("vlan_id", help="VLAN number to create or remove", action="store", type=int)
    parser.add_argument(
        "--name",
        help="Specify VLAN name",
        action="store",
        dest="vlan_name",
        type=str
    )
    parser.add_argument("--remove", help="Remove the given VLAN ID", action="store_true")

    cli_args = parser.parse_args()
    vlan_id = cli_args.vlan_id
    remove = cli_args.remove
    vlan_name = cli_args.vlan_name

    # Check if VLAN already exists
    check_vlan = check_vlan_exists(eapi_conn, vlan_id)

    # check if action is remove or add
    if remove:
        if check_vlan:
            print "VLAN exists, removing it"
            command_str = 'no vlan {}'.format(vlan_id)
            eapi_conn.config([command_str])
        else:
            print "VLAN does not exist, no action required"

    else:

        if check_vlan:
            if vlan_name is not None and check_vlan != vlan_name:
                print "VLAN already exists, setting VLAN name"
                configure_vlan(eapi_conn, vlan_id, vlan_name)
            else:
                print "VLAN already exists, no action required"

        else:
            print "Adding VLAN including vlan_name (if present)"
            configure_vlan(eapi_conn, vlan_id, vlan_name)
Ejemplo n.º 3
0
def main():
	'''
	Simple Ansible Module to create an Arista VLAN
	'''
	
	# This is to create an object of the class AnsibleModule defined in the following: https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/basic.py
	module = AnsibleModule(
		argument_spec = dict(
			vlan_id = dict(required=True),
			vlan_name = dict(required=False),
			eapi_username = dict(required=True),
			eapi_password = dict(required=True),
			eapi_hostname = dict(required=True),
			eapi_port = dict(required=False, type='int'),
		)
	)

	arista_params = {
		'eapi_username': '******',
		'eapi_password': '******',
		'eapi_hostname': 'hostname',
		'eapi_port': 'port',	
	}

	arista_dict = {}

	# Map the eapi_* names to the names required by eapilib
	for ansible_name, arista_name in arista_params.items():
		if ansible_name in module.params:
			arista_dict[arista_name] = module.params[ansible_name]
	
	eapi_conn = eapilib.create_connection(**arista_dict)
	
	vlan_id = module.params['vlan_id']
	vlan_name = module.params.get('vlan_name')

	# Check if VLAN already exists
	check_vlan = check_vlan_exists(eapi_conn, vlan_id)

	if check_vlan:
		if vlan_name is not None and check_vlan != vlan_name:
			configure_vlan(eapi_conn, vlan_id, vlan_name)
			module.exit_json(msg="VLAN already exists, setting VLAN name", changed=True)
		else:
			module.exit_json(msg="VLAN already exists, no action required", changed=False)

	else:
		configure_vlan(eapi_conn, vlan_id, vlan_name)
		module.exit_json(msg="Adding VLAN including vlan_name (if present)", changed=True)
Ejemplo n.º 4
0
def inventory_dispatcher():
    '''
    Dispatcher for calling SSH, onePK, or eAPI based on the
    NetworkDevice.device_class
    '''

    DEBUG = True

    net_devices = NetworkDevice.objects.all()

    for a_device in net_devices:

        if 'ssh' in a_device.device_class:
            if DEBUG:
                print "SSH inventory call: {} {}\n".format(a_device.device_name,
                                                           a_device.device_class)
            ssh_connect = SSHConnection(a_device)
            output = ssh_connect.send_command('show version\n')
            inventory_obj = CLASS_MAPPER[a_device.device_class](a_device, output)

            inventory_obj.find_vendor()
            inventory_obj.find_model()
            inventory_obj.find_device_type()
            inventory_obj.find_os_version()
            inventory_obj.find_serial_number()
            inventory_obj.find_uptime()

            print 'Inventory gathering for device complete'
            print_inventory(a_device)

        elif 'onepk' in a_device.device_class:
            if DEBUG:
                print "onePK inventory call: {} {}\n".format(a_device.device_name,
                                                             a_device.device_class)

            # FIX - pin_file is hard-coded
            onepk_connect = onepk_helper.NetworkDevice(
                ip=a_device.ip_address,
                username=a_device.credentials.username,
                password=a_device.credentials.password,
                port=a_device.api_port,
                pin_file='pynet-rtr1-pin.txt'
            )

            onepk_connect.establish_session()

            a_device.vendor = 'cisco'
            part_number = onepk_connect.net_element.properties.product_id
            a_device.model = onepk_find_model(part_number)
            a_device.device_type = onepk_find_device_type(a_device.model)
            sys_descr = onepk_connect.net_element.properties.sys_descr
            a_device.os_version = onepk_find_os_version(sys_descr)
            a_device.serial_number = onepk_connect.net_element.properties.SerialNo
            a_device.uptime_seconds = onepk_connect.net_element.properties.sys_uptime
            a_device.save()

            onepk_connect.disconnect()

            print 'Inventory gathering for device complete'
            print_inventory(a_device)

        elif 'eapi' in a_device.device_class:

            if DEBUG:
                print "eAPI inventory call: {} {}\n".format(a_device.device_name,
                                                            a_device.device_class)

            eapi_conn = eapilib.create_connection(
                hostname=a_device.ip_address,
                username=a_device.credentials.username,
                password=a_device.credentials.password,
                port=a_device.api_port
            )

            response = eapi_conn.run_commands(['show version'])
            arista_dict = response[0]

            a_device.vendor = 'arista'
            a_device.model = arista_dict['modelName']

            # Should really be a function
            if a_device.model == 'vEOS':
                a_device.device_type = 'switch'
            else:
                a_device.device_type = ''
            a_device.os_version = arista_dict['version']

            a_device.serial_number = arista_dict['serialNumber']
            # Should normalize the MacAddress format
            if not a_device.serial_number:
                a_device.serial_number = arista_dict['systemMacAddress']

            # bootupTimestamp is since epoch. Requires time on router to be right.
            uptime_seconds = arista_dict['bootupTimestamp']
            time_delta = time.time() - int(uptime_seconds)
            a_device.uptime_seconds = int(time_delta)

            a_device.save()

            print 'Inventory gathering for device complete'
            print_inventory(a_device)

        else:
            # invalid condition / exception
            pass
Ejemplo n.º 5
0
def inventory_dispatcher():
    '''
    Dispatcher for calling SSH, onePK, or eAPI based on the
    NetworkDevice.device_class
    '''

    DEBUG = True

    net_devices = NetworkDevice.objects.all()

    for a_device in net_devices:

        if 'ssh' in a_device.device_class:
            if DEBUG:
                print "SSH inventory call: {} {}\n".format(
                    a_device.device_name, a_device.device_class)
            ssh_connect = SSHConnection(a_device)
            output = ssh_connect.send_command('show version\n')
            inventory_obj = CLASS_MAPPER[a_device.device_class](a_device,
                                                                output)

            inventory_obj.find_vendor()
            inventory_obj.find_model()
            inventory_obj.find_device_type()
            inventory_obj.find_os_version()
            inventory_obj.find_serial_number()
            inventory_obj.find_uptime()

            print 'Inventory gathering for device complete'
            print_inventory(a_device)

        elif 'onepk' in a_device.device_class:
            if DEBUG:
                print "onePK inventory call: {} {}\n".format(
                    a_device.device_name, a_device.device_class)

            # FIX - pin_file is hard-coded
            onepk_connect = onepk_helper.NetworkDevice(
                ip=a_device.ip_address,
                username=a_device.credentials.username,
                password=a_device.credentials.password,
                port=a_device.api_port,
                pin_file='pynet-rtr1-pin.txt')

            onepk_connect.establish_session()

            a_device.vendor = 'cisco'
            part_number = onepk_connect.net_element.properties.product_id
            a_device.model = onepk_find_model(part_number)
            a_device.device_type = onepk_find_device_type(a_device.model)
            sys_descr = onepk_connect.net_element.properties.sys_descr
            a_device.os_version = onepk_find_os_version(sys_descr)
            a_device.serial_number = onepk_connect.net_element.properties.SerialNo
            a_device.uptime_seconds = onepk_connect.net_element.properties.sys_uptime
            a_device.save()

            onepk_connect.disconnect()

            print 'Inventory gathering for device complete'
            print_inventory(a_device)

        elif 'eapi' in a_device.device_class:

            if DEBUG:
                print "eAPI inventory call: {} {}\n".format(
                    a_device.device_name, a_device.device_class)

            eapi_conn = eapilib.create_connection(
                hostname=a_device.ip_address,
                username=a_device.credentials.username,
                password=a_device.credentials.password,
                port=a_device.api_port)

            response = eapi_conn.run_commands(['show version'])
            arista_dict = response[0]

            a_device.vendor = 'arista'
            a_device.model = arista_dict['modelName']

            # Should really be a function
            if a_device.model == 'vEOS':
                a_device.device_type = 'switch'
            else:
                a_device.device_type = ''
            a_device.os_version = arista_dict['version']

            a_device.serial_number = arista_dict['serialNumber']
            # Should normalize the MacAddress format
            if not a_device.serial_number:
                a_device.serial_number = arista_dict['systemMacAddress']

            # bootupTimestamp is since epoch. Requires time on router to be right.
            uptime_seconds = arista_dict['bootupTimestamp']
            time_delta = time.time() - int(uptime_seconds)
            a_device.uptime_seconds = int(time_delta)

            a_device.save()

            print 'Inventory gathering for device complete'
            print_inventory(a_device)

        else:
            # invalid condition / exception
            pass
Ejemplo n.º 6
0
 def __init__(self, **params):
     """ 
     this function initializes the EAPI calls:
     """
     self.sw = create_connection( **params )
Ejemplo n.º 7
0
def gather_inventory(DEBUG=False):
    '''
        Gathers inventory for all network devices in the database
    '''
    network_devices = NetworkDevice.objects.all()

    class_select = {'cisco_ios_ssh': GatherInventory,
                    'arista_eos_ssh': AristaGatherInventory}

    for a_device in network_devices:
        if 'ssh' in a_device.device_class:
            # instanciate SSHConnection object, connect to SSH device, turn off
            # paging and send show version command. Parse output to update
            # network device object then print the inventory of the object

            some_obj = SSHConnection(a_device)
            some_obj.establish_conn()
            some_obj.disable_paging()
            output = some_obj.send_command('show version\n')

            obj_inventory = class_select[a_device.device_class](a_device, output)
            obj_inventory.find_device_type()
            obj_inventory.find_model()
            obj_inventory.find_os_version()
            obj_inventory.find_serial_number()
            obj_inventory.find_up_time()
            obj_inventory.find_vendor()

            print_inventory(a_device)

        elif 'onepk' in a_device.device_class:
            # instanciate onePK object through onepk_helper, connect to onePK
            # device, using onePK methods update network device object then
            # print the inventory of the object

            if DEBUG:
                print('onePK inventory for {} {}'.format(a_device.device_name,
                                                         a_device.device_class))

            pin_file_path = '/home/dholcombe/CISCO/pynet-rtr1-pin.txt'

            onepk_creds = dict(ip=a_device.ip_address,
                               username=a_device.credentials.username,
                               password=a_device.credentials.password,
                               pin_file=pin_file_path,
                               port=a_device.api_port)

            onepk_device = OnepkDevice(**onepk_creds)

            onepk_device.establish_session()

            # gather_inventory_onepk()
            a_device.device_type = 'router'
            a_device.vendor = 'Cisco OnePK'
            a_device.model = onepk_device.net_element.properties.product_id
            a_device.serial_number = onepk_device.net_element.properties.SerialNo
            a_device.uptime_seconds = onepk_device.net_element.properties.sys_uptime

            match = re.search(r'Version.*', onepk_device.net_element.properties.sys_descr)
            if match:
                a_device.os_version = match.group()

            onepk_device.disconnect()
            a_device.save()

            print_inventory(a_device)

        elif 'eapi' in a_device.device_class:

            if DEBUG:
                print('eapi inventory for {} {}'.format(a_device.device_name,
                                                        a_device.device_class))
            # this could have been a function gather_inventory_eapi().
            # Credentials for the api connection
            eapi_creds = dict(hostname=a_device.ip_address,
                              username=a_device.credentials.username,
                              password=a_device.credentials.password,
                              port=a_device.api_port)

            # create url string to the api device and enables some funcitons
            # like run_command
            eapi = eapilib.create_connection(**eapi_creds)

            # send 'show version command' (returns a list)
            # pops the output (dict)
            show_version = eapi.run_commands(['show version']).pop()

            # assigns variables using show version output
            a_device.vendor = 'Arista API'
            a_device.device_type = 'Switch'
            a_device.model = show_version['version']
            a_device.serial_number = show_version['systemMacAddress']
            a_device.uptime_seconds = show_version['bootupTimestamp']

            a_device.save()

            print_inventory(a_device)
Ejemplo n.º 8
0
def retrieve_config(DEBUG=False):
    '''
        Gathers inventory for all network devices in the database
    '''
    network_devices = NetworkDevice.objects.all()
    cfg_path = '/home/dholcombe/cfgs/'

    for a_device in network_devices:
        if 'ssh' in a_device.device_class:
            # instanciate SSHConnection object, connect to SSH device, turn off
            # paging and send show version command. Parse output to update
            # network device object then print the inventory of the object

            ssh = SSHConnection(a_device)
            ssh.establish_conn()
            ssh.disable_paging()
            ssh.enable_mode()
            output = ssh.send_command('show run\n')

            print output

            # create the file name if one does not exist
            if not a_device.cfg_file:
                a_device.cfg_file = cfg_path + a_device.device_name + '.txt'

            with open(a_device.cfg_file, 'w') as output_file:
                output_file.write(output)

        elif 'onepk' in a_device.device_class:
            # instanciate onePK object through onepk_helper, connect to onePK
            # device, using onePK methods update network device object then
            # print the inventory of the object

            if DEBUG:
                print('onePK inventory for {} {}'.format(a_device.device_name,
                                                         a_device.device_class))

            pass

        elif 'eapi' in a_device.device_class:

            if DEBUG:
                print('eapi inventory for {} {}'.format(a_device.device_name,
                                                        a_device.device_class))
            # this could have been a function gather_inventory_eapi().
            # Credentials for the api connection
            eapi_creds = dict(hostname=a_device.ip_address,
                              username=a_device.credentials.username,
                              password=a_device.credentials.password,
                              port=a_device.api_port)

            # create url string to the api device and enables some funcitons
            # like run_command
            eapi = eapilib.create_connection(**eapi_creds)

            # send 'show version command' (returns a list)
            # pops the output (dict)
            output = eapi.run_commands(['show version']).pop()

            print output


            # create the file name if one does not exist
            if not a_device.cfg_file:
                a_device.cfg_file = cfg_path + a_device.device_name + '.txt'

            with open(a_device.cfg_file, 'wb') as eapi_file:
                json.dump(output, eapi_file)
Ejemplo n.º 9
0
line as follows:
   python eapi_vlan.py --name blue 100     # add VLAN100, name blue

If you call the script with the --remove option, the VLAN will be removed.
   python eapi_vlan.py --remove 100          # remove VLAN100

Once again only remove the VLAN if it exists on the switch.  You will probably want to use Python's argparse to accomplish the argument processing.
'''

import eapilib
import jsonrpclib
import argparse
from pprint import pprint

login_dict = dict()
eapi_conn = eapilib.create_connection(**login_dict)


def check_vlan(vlan_id):
    #check if Vlan exsists if not return name
    try:
        output = run_commands(['show vlan {}'.format(vlan_id)])
        output = output[0]['vlans']
        return output[vlan_id]['name']
    except:
        pass
    return False


def config_commands(commands):
    #run config commands from string