def Connect():
    """Connects to the Arista router.
  
  Returns: pyeapi.Node, the connected router.
  """
    pyeapi.load_config('eapi.conf')
    return pyeapi.connect_to('arista')
Esempio n. 2
0
    def connect(self):
        if self.config is not None:
            pyeapi.load_config(self.config)

        config = dict()

        if self.connection is not None:
            config = pyeapi.config_for(self.connection)
            if not config:
                msg = 'Connection name "{}" not found'.format(self.connection)

        for key in self.__attributes__:
            if getattr(self, key) is not None:
                config[key] = getattr(self, key)

        if 'transport' not in config:
            raise ValueError('Connection must define a transport')

        connection = pyeapi.client.make_connection(**config)
        node = pyeapi.client.Node(connection, **config)

        try:
            node.enable('show version')
        except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError):
            raise ValueError('unable to connect to {}'.format(node))
        return node
Esempio n. 3
0
    def connect(self):
        if self.params['config']:
            pyeapi.load_config(self.params['config'])

        config = dict()

        if self.params['connection']:
            config = pyeapi.config_for(self.params['connection'])
            if not config:
                msg = 'Connection name "%s" not found' % self.params[
                    'connection']
                self.fail(msg)

        if self.params['username']:
            config['username'] = self.params['username']

        if self.params['password']:
            config['password'] = self.params['password']

        if self.params['transport']:
            config['transport'] = self.params['transport']

        if self.params['port']:
            config['port'] = self.params['port']

        if self.params['host']:
            config['host'] = self.params['host']

        if 'transport' not in config:
            self.fail('Connection must define a transport')

        connection = pyeapi.client.make_connection(**config)
        self.log('Creating connection with autorefresh=%s' % self._autorefresh)
        node = pyeapi.client.Node(connection,
                                  autorefresh=self._autorefresh,
                                  **config)

        try:
            resp = node.enable('show version')
            self.debug('eos_version', resp[0]['result']['version'])
            self.debug('eos_model', resp[0]['result']['modelName'])
        except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError):
            self.fail('unable to connect to %s' % node)
        else:
            self.log('Connected to node %s' % node)
            self.debug('node', str(node))

        return node
Esempio n. 4
0
	def __init__(self, num=0):
		sw = ['core1', 'sw1', 'sw2', 'sw3', 'sw4', 'sw5', 'spine1', 'spine2']
		name = sw[num]
		# Config for switch access filepath
		conf = 'eapi.conf'
		self.sw = sw
		self.name = name
		self.conf = conf
		pyeapi.load_config(conf)
		try:
			node = pyeapi.connect_to(sw[num])
			node.enable('show hostname')
			node.conf('hostname %s' % sw[num])
			self.node = node
		except Exception:
			print ('* Failed to connect to switch! Check config at \'/%s\' *' % conf)
    def connect(self):
        if self.params['config']:
            pyeapi.load_config(self.params['config'])

        config = dict()

        if self.params['connection']:
            config = pyeapi.config_for(self.params['connection'])
            if not config:
                msg = 'Connection name "%s" not found' % self.params['connection']
                self.fail(msg)

        if self.params['username']:
            config['username'] = self.params['username']

        if self.params['password']:
            config['password'] = self.params['password']

        if self.params['transport']:
            config['transport'] = self.params['transport']

        if self.params['port']:
            config['port'] = self.params['port']

        if self.params['host']:
            config['host'] = self.params['host']

        if 'transport' not in config:
            self.fail('Connection must define a transport')

        connection = pyeapi.client.make_connection(**config)
        self.log('Creating connection with autorefresh=%s' % self._autorefresh)
        node = pyeapi.client.Node(connection, autorefresh=self._autorefresh,
                                  **config)

        try:
            resp = node.enable('show version')
            self.debug('eos_version', resp[0]['result']['version'])
            self.debug('eos_model', resp[0]['result']['modelName'])
        except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError):
            self.fail('unable to connect to %s' % node)
        else:
            self.log('Connected to node %s' % node)
            self.debug('node', str(node))

        return node
    def connect(self):
        if self.params["config"]:
            pyeapi.load_config(self.params["config"])

        config = dict()

        if self.params["connection"]:
            config = pyeapi.config_for(self.params["connection"])
            if not config:
                msg = 'Connection name "%s" not found' % self.params["connection"]
                self.fail(msg)

        if self.params["username"]:
            config["username"] = self.params["username"]

        if self.params["password"]:
            config["password"] = self.params["password"]

        if self.params["transport"]:
            config["transport"] = self.params["transport"]

        if self.params["port"]:
            config["port"] = self.params["port"]

        if self.params["host"]:
            config["host"] = self.params["host"]

        if "transport" not in config:
            self.fail("Connection must define a transport")

        connection = pyeapi.client.make_connection(**config)
        self.log("Creating connection with autorefresh=%s" % self._autorefresh)
        node = pyeapi.client.Node(connection, autorefresh=self._autorefresh, **config)

        try:
            resp = node.enable("show version")
            self.debug("eos_version", resp[0]["result"]["version"])
            self.debug("eos_model", resp[0]["result"]["modelName"])
        except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError):
            self.fail("unable to connect to %s" % node)
        else:
            self.log("Connected to node %s" % node)
            self.debug("node", str(node))

        return node
Esempio n. 7
0
    def connect(self):
        if self.params['config']:
            pyeapi.load_config(self.params['config'])

        config = dict()

        if self.params['connection']:
            config = pyeapi.config_for(self.params['connection'])
            if not config:
                msg = 'Connection name "%s" not found' % self.params['connection']
                self.fail(msg)

        if self.params['username']:
            config['username'] = self.params['username']

        if self.params['password']:
            config['password'] = self.params['password']

        if self.params['transport']:
            config['transport'] = self.params['transport']

        if self.params['port']:
            config['port'] = self.params['port']

        if self.params['host']:
            config['host'] = self.params['host']

        if 'transport' not in config:
            self.fail('Connection must define a transport')

        connection = pyeapi.client.make_connection(**config)
        node = pyeapi.client.Node(connection)

        try:
            node.enable('show version')
        except (pyeapi.eapilib.ConnectionError, pyeapi.eapilib.CommandError):
            self.fail('unable to connect to %s' % node)
        else:
            self.log('Connected to node %s' % node)
            self.debug('node', str(node))

        return node
Esempio n. 8
0
def setup():
    pyeapi.load_config(os.path.join(here, 'fixtures/eapi.conf'))
    for name in pyeapi.client.config.connections:
        if name != 'localhost':
            nodes[name] = pyeapi.connect_to(name)

    assert len(nodes) > 0, 'no test nodes loaded, does eapi.conf exist?'

    modules = os.environ.get('ANSIBLE_TEST_CASES')

    testcases_home = os.path.join(here, 'testcases')
    filenames = os.listdir(testcases_home)

    for module in filter_modules(modules, filenames):
        path = os.path.join(testcases_home, module)
        definition = yaml.load(open(path))

        defaults = definition.get('defaults', {})
        for testcase in definition['testcases']:
            kwargs = defaults.copy()
            kwargs.update(testcase)
            testcases.append(TestCase(**kwargs))
Esempio n. 9
0
def setup():
    pyeapi.load_config(os.path.join(here, 'fixtures/eapi.conf'))
    for name in pyeapi.client.config.connections:
        if name != 'localhost':
            nodes[name] = pyeapi.connect_to(name)

    assert len(nodes) > 0, 'no test nodes loaded, does eapi.conf exist?'

    modules = os.environ.get('ANSIBLE_TEST_CASES')

    testcases_home = os.path.join(here, 'testcases')
    filenames = os.listdir(testcases_home)

    for module in filter_modules(modules, filenames):
        path = os.path.join(testcases_home, module)
        definition = yaml.load(open(path))

        defaults = definition.get('defaults', {})
        for testcase in definition['testcases']:
            kwargs = defaults.copy()
            kwargs.update(testcase)
            testcases.append(TestCase(**kwargs))
Esempio n. 10
0
#!/usr/bin/env python2

import pyeapi

pyeapi.load_config('Targets.conf')
student_switch = pyeapi.connect_to('Student-06')

response = student_switch.enable(['show version'])

print response[0]['result']['version']
Esempio n. 11
0
#!/usr/bin/env python

import pyeapi
from pprint import pprint

pyeapi.load_config("nodes.conf")
switch = pyeapi.connect_to('pynet-sw3')

data_returned = switch.enable('show interfaces')

interfaces = data_returned[0].get("result").get('interfaces')

for interface, data in interfaces.items():
    if not data.get('interfaceCounters'):
        del interfaces[interface]

print '{:<12} {:<9} {:<9}'.format('Interface','inOctets','outOctets')
for interface, data in interfaces.items():
    in_octets = data['interfaceCounters']['inOctets']
    out_octets = data['interfaceCounters']['outOctets']
    print '{:<12} {:<9} {:<9}'.format(interface, in_octets, out_octets)
Esempio n. 12
0
#!/usr/bin/env python

import pyeapi

pyeapi.load_config('nodes.conf')
node = pyeapi.connect_to('veos01')

output = node.enable('show version')

print 'My System MAC address is', output[0]['result']['systemMacAddress']
Esempio n. 13
0
#!/usr/bin/env python2
import pyeapi
from graphviz import Digraph

pyeapi.load_config('.eapi.conf')

#test devices in lab see .eapi.conf file in same directory for connection parameters
switches = ['arista249', 'arista250']


def gather_topos(devices):
    """
    Function which takes a list of devices as input and runs the lldp neigh command against them
    using the Arista pyeapi library
    :param devices:
    :return: list of lldp neigh output
    """
    topo = []
    for switch in devices:
        node = pyeapi.connect_to(switch)
        output = node.enable('show lldp neighbors')
        device_neigh = {
            'name': switch,
            'neighbors': (output[0]['result']['lldpNeighbors'])
        }
        topo.append(device_neigh)
    return topo


# runs the gather_topos using the switches VAR from above and captures in the all_devs_neigh... VAR
all_devs_neighbors_output = gather_topos(switches)
Esempio n. 14
0
"""
site-check.py
Automation script to connect to Arista devices and record state to a txt file.
To be run Pre and Post maintenance event to check for state differences.
https://github.com/brentnowak/arista-tools
"""

import json
import pyeapi
import datetime
from collections import OrderedDict

switches = ['switch-name']
pyeapi.load_config('nodes.conf')


def sorted_dict(d):
    """
    :param dict: unsorted dictionary
    :return: JSON formatted ordered dictionary by key
    """
    return json.dumps(OrderedDict(sorted(dict_remove_keys(d).items())))


def dict_remove_keys(d):
    """
    Remove dictionary keys that clutter report
    """
    filter = ("lastMove", "sflow", "flowcontrol_send", "flowcontrol_receive",
              "routeAction", "hardwareProgrammed", "kernelProgrammed",
              "directlyConnected", "ttl", "type", "entryType", "moves",
Esempio n. 15
0
 try:
     conn = pymongo.MongoClient('10.0.0.0', 27017)
 except pymongo.errors.ConnectionFailure, e:
     print "Could not connect to MongoDB: %s" % e
 # connecting to the database named neteng
 db = conn.neteng
 # load predefined listing of nodes and values of the format:
 # each device
 #[connection:$DEVICE_NAME]
 #host: $IP
 # once per file
 #[DEFAULT]
 #username: $USER
 #password: $PASS
 #transport: https
 pyeapi.load_config('~/.eapi.conf')
 #reset collection ileaf spine eleaf icore
 db.drop_collection('ileaf_ospf')
 db.drop_collection('spine_ospf')
 db.drop_collection('eleaf_ospf')
 db.drop_collection('icore_ospf')
 threads = []
 # loop through ileaf arista devices
 for il in ileaf:
     t = threading.Thread(target=ileaf_collect, args=(il,))
     threads.append(t)
     t.start()
 # loop through spine arista devices
 for sp in spine:
     t = threading.Thread(target=spine_collect, args=(sp,))
     threads.append(t)



import pyeapi
from pprint import pprint as pp
pyeapi.load_config('/home/carl/Desktop/USBNetworkAutomation-Part2/Api/.eapi.conf')
node = pyeapi.connect_to('veos01')

lldpNeighbors = node.enable('show lldp neighbors')[0]['result']['lldpNeighbors']

for i in lldpNeighbors:
    print(i)
    print(node.config(['interface '+i['port'] , 'description connected to '+i['neighborDevice']+' on interface '+i['neighborPort']]))



Esempio n. 17
0
def load_config(uri):
    pyeapi.load_config(uri)
    br1 = pyeapi.connect_to('test')
    pp(br1.enable('show version'))