Ejemplo n.º 1
0
def main():
    module = AnsibleModule(argument_spec=dict(host=dict(required=True),
                                              user=dict(
                                                  required=False,
                                                  default=os.getenv('USER')),
                                              passwd=dict(required=False,
                                                          default=None)),
                           supports_check_mode=False)

    m_args = module.params
    m_results = dict(changed=False)
    dev = Device(m_args['host'], user=m_args['user'], passwd=m_args['passwd'])
    try:
        dev.open()
    except Exception as err:
        msg = 'unable to connect to {}: {}'.format(m_args['host'], str(err))
        module.fail_json(msg=msg)
        return
    results = {}
    lldp_results = []
    try:
        lldp = LLDPNeighborTable(dev)
        lldp.get()
        lldp = json.loads(json.dumps(lldp, cls=TableJSONEncoder))
    except Exception as err:
        dev.close()
        module.fail_json(msg=err)
        return
    dev.close()
    module.exit_json(results=lldp)
Ejemplo n.º 2
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            host=dict(required=True),
            user=dict(required=False, default=os.getenv('USER')),
            passwd=dict(required=False, default=None)),
        supports_check_mode=False)

    m_args = module.params
    m_results = dict(changed=False)
    dev = Device(m_args['host'], user=m_args['user'], passwd=m_args['passwd'])
    try:
        dev.open()
    except Exception as err:
        msg = 'unable to connect to {}: {}'.format(m_args['host'], str(err))
        module.fail_json(msg=msg)
        return
    results = {}
    lldp_results = []
    try:
        lldp = LLDPNeighborTable(dev)
        lldp.get()
        lldp = json.loads(json.dumps(lldp, cls=TableJSONEncoder))
    except Exception as err:
        dev.close()
        module.fail_json(msg=err)
        return
    dev.close()
    module.exit_json(results=lldp)
Ejemplo n.º 3
0
 def test_keys__keys_pipe(self, mock_execute):
     from jnpr.junos.op.lldp import LLDPNeighborTable
     mock_execute.side_effect = self._mock_manager
     self.lldp = LLDPNeighborTable(self.dev)
     self.lldp.get()
     self.assertEqual(self.lldp.keys(),
                      ['et-0/0/48', 'et-0/0/49', 'xe-0/0/13'])
Ejemplo n.º 4
0
 def test_table_json(self):
     lldp = LLDPNeighborTable(self.dev)
     lldp.get('et-0/1/1')
     json = '{"et-0/1/1": {"remote_port_desc": "et-1/1/1", '\
         '"local_int": "et-0/1/1", "remote_sysname": "highlife", '\
         '"local_parent": "-", "remote_chassis_id": "4c:96:14:f3:d5:20", '\
         '"remote_type": "Mac address"}}'
     self.assertEqual(lldp.to_json(), json)
Ejemplo n.º 5
0
 def test_table_json(self):
     lldp = LLDPNeighborTable(self.dev)
     lldp.get('et-0/1/1')
     json = '{"et-0/1/1": {"remote_port_desc": "et-1/1/1", '\
         '"local_int": "et-0/1/1", "remote_sysname": "highlife", '\
         '"local_parent": "-", "remote_chassis_id": "4c:96:14:f3:d5:20", '\
         '"remote_type": "Mac address"}}'
     self.assertEqual(lldp.to_json(), json)
class Neighbors(Util):
    """Junos Neighbor Class

    :param dev: connected device
    :type dev: jnpr.junos.Device

    :reises: jnpr.junos.exception
    """

    @property
    def lldp(self):
        if not hasattr(self, '_lldp'):
            self._lldp = LLDPNeighborTable(self.dev)
        return self._lldp.get()

    @property
    def isis(self):
        if not hasattr(self, '_isis'):
            self._isis = IsisAdjacencyTable(self.dev)
        return self._isis.get()

    @property
    def ospf(self):
        if not hasattr(self, '_ospf'):
            self._ospf = OspfNeighborTable(self.dev)
        return self._ospf.get()

    def all(self):
        """Return ALL Neighbors with protocols

        :return: dict of neighbors with IFD as key
        :rtype: dict
        """
        neighbors = defaultdict(lambda: {'protocols': set()})
        for lldp in self.lldp:
            neighbors[lldp.local_int]['hostname'] = lldp.remote_sysname
            neighbors[lldp.local_int]['protocols'].add('lldp')
        for isis in self.isis:
            ifd, unit = isis.interface_name.split('.')
            if 'hostname' not in neighbors[ifd]:
                neighbors[ifd]['hostname'] = isis.system_name
            neighbors[ifd]['protocols'].add('isis')
        for ospf in self.ospf:
            ifd, unit = ospf.interface_name.split('.')
            if 'hostname' not in neighbors[ifd]:
                try:
                    dns_name = socket.gethostbyaddr(ospf.neighbor_id)[0]
                    neighbors[ifd]['hostname'] = dns_name
                except socket.herror:
                    neighbors[ifd]['hostname'] = ospf.neighbor_id
            neighbors[ifd]['protocols'].add('ospf')
        return neighbors

    def display(self):
        """Display ALL Neighbors"""
        print("Neighbors:")
        print("%-16s %-16s %s" % ('Interface', 'Hostname', 'Protocols'))
        for ifd, attributes in self.all().iteritems():
            print("%-16s %-16s %s" % (ifd, attributes['hostname'],
                  ", ".join(attributes['protocols'])))
Ejemplo n.º 7
0
 def test_keys__keys_pipe(self, mock_execute):
     from jnpr.junos.op.lldp import LLDPNeighborTable
     mock_execute.side_effect = self._mock_manager
     self.lldp = LLDPNeighborTable(self.dev)
     self.lldp.get()
     self.assertEqual(
         self.lldp.keys(), [
             'et-0/0/48', 'et-0/0/49', 'xe-0/0/13'])
Ejemplo n.º 8
0
def compare_lldp_info():
    expected_topology = {
        'fxp0': {
            'Chassis_ID': '50:c7:09:a3:c5:9d',
            'System_Name': 'gw.pod3.cce'
        },
        'xe-1/1/0': {
            'Chassis_ID': '50:c7:09:bb:64:dc',
            'System_Name': 'spine2.pod3.cce'
        },
        'xe-1/1/1': {
            'Chassis_ID': '50:c7:09:c5:8b:0c',
            'System_Name': 'spine1.pod3.cce'
        },
        'xe-1/1/2': {
            'Chassis_ID': 'abc123',
            'System_Name': 'unknown host'
        }
    }
    try:
        with Device() as dev:
            lldp = LLDPNeighborTable(dev)
            lldp.get()
            for item in lldp:
                if item['local_int'] in expected_topology.keys() \
                        and item['remote_chassis_id'] == expected_topology[item['local_int']['Chassis_ID']] \
                        and item['remote_sysname'] == expected_topology[item['local_int']['System_Name']]:
                    jcs.syslog(
                        'external.info',
                        "{0}: Expected interface found.".format(
                            item['local_int']))
                else:
                    jcs.syslog(
                        'external.warn',
                        "{0}: Cabling mismatch detected.".format(
                            item['local_int']))
                    jcs.syslog(
                        'external.warn',
                        "{0}: Disabling interface.".format(item['local_int']))
                    disable_interface(item['local_int'])
    except Exception as inst:
        jcs.syslog('external.warn',
                   "{0}: Unable to verify LLDP information.".format(inst))
Ejemplo n.º 9
0
def main():
    try:
        password = get_password()
        router = connect_to_router(args.router, args.username, password)
        router.open()
        neighbors = LLDPNeighborTable(router)
        neighbors.get()
        output_json = json.loads(neighbors.to_json())
        for i in output_json:
            print 'local interface is ' + str(
                i
            ) + ' and remote interface is ' + output_json[i]['remote_port_id']
    except ConnectAuthError as e:
        print e
    except ConnectRefusedError as e:
        print e
    except ConnectTimeoutError as e:
        print e
    except ConnectError as e:
        print e
Ejemplo n.º 10
0
from jnpr.junos import Device
from jnpr.junos.op.lldp import LLDPNeighborTable

port_list=["2221", "2222", "2223"]

for item in port_list:
 dev=Device(host="127.0.0.1", user="******", password="******", port=item)
 dev.open()
 lldp_neighbors=LLDPNeighborTable(dev)
 lldp_neighbors.get()
 print "\nstatus of LLDP neighbors of " + dev.facts["hostname"]+ ":"
 for xxx in lldp_neighbors:
  print "interface " + xxx.local_int + " has this neighbor: " + xxx.remote_sysname
 dev.close()

Ejemplo n.º 11
0
from jnpr.junos import Device
from jnpr.junos.op.lldp import LLDPNeighborTable
import json

device = Device(host='111.111.111.111', user='******', password='******')
device.open()
neighbors = LLDPNeighborTable(device)
neighbors.get()
output_json = json.loads(neighbors.to_json())
for i in output_json:
    print 'local interface is ' + str(
        i) + ' and remote interface is ' + output_json[i]['remote_port_id']
Ejemplo n.º 12
0
class TestFactoryTable(unittest.TestCase):
    @patch('ncclient.manager.connect')
    def setUp(self, mock_connect):
        mock_connect.side_effect = self._mock_manager
        self.dev = Device(host='1.1.1.1', user='******', password='******',
                          gather_facts=False)
        self.dev.open()
        self.table = Table(dev=self.dev)
        self.ppt = PhyPortTable(self.dev)

    def test_config_constructor(self):
        self.assertTrue(isinstance(self.table.D, Device))

    def test_table_hostname(self):
        self.assertEqual(self.table.hostname, '1.1.1.1')

    def test_table_is_container(self):
        self.assertTrue(self.table.is_container)

    def test_table_repr_xml_none(self):
        self.assertEqual(repr(self.table), 'Table:1.1.1.1 - Table empty')

    def test_table_view_setter_ValueError(self):
        try:
            self.table.view = 'test'
        except Exception as ex:
            self.assertEqual(ex.__class__, ValueError)

    @patch('jnpr.junos.Device.execute')
    def test_keys_RuntimeError(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.ppt.ITEM_NAME_XPATH = 1
        self.assertRaises(RuntimeError, self.ppt.keys)

    @patch('jnpr.junos.Device.execute')
    def test_keys__keys_composite(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.ppt.ITEM_NAME_XPATH = ['name', 'missing', 'mtu']
        self.assertEqual(self.ppt.keys(),
                         [('ge-0/0/0', None, '1514'), ('ge-0/0/1', None, '1514')])

    @patch('jnpr.junos.Device.execute')
    def test_keys__keys_pipe(self, mock_execute):
        from jnpr.junos.op.lldp import LLDPNeighborTable
        mock_execute.side_effect = self._mock_manager
        self.lldp = LLDPNeighborTable(self.dev)
        self.lldp.get()
        self.assertEqual(self.lldp.keys(), ['et-0/0/48', 'et-0/0/49', 'xe-0/0/13'])

    @patch('jnpr.junos.Device.execute')
    def test_table_repr_xml_not_none(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.table.xml = self.ppt.xml
        self.table.ITEM_XPATH = self.ppt.ITEM_XPATH
        self.assertEqual(repr(self.table), 'Table:1.1.1.1: 2 items')

    @patch('jnpr.junos.Device.execute')
    def test_table_get_keys_values(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(self.ppt.keys(), ['ge-0/0/0', 'ge-0/0/1'])
        self.assertEqual(len(self.ppt.values()), 2)
        self.ppt.view = None
        self.assertEqual(len(self.ppt.values()), 2)

    @patch('jnpr.junos.Device.execute')
    def test_table__getitem__(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(self.ppt[0].ITEM_NAME_XPATH, 'name')

    @patch('jnpr.junos.Device.execute')
    def test_table__getitem__slice(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(self.ppt[:1][0].__class__.__name__, 'PhyPortView')

    @patch('jnpr.junos.Device.execute')
    def test_table__getitem__tuple(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(self.ppt[('ge-0/0/0',)], None)

    @patch('jnpr.junos.Device.execute')
    def test_table__contains__(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertTrue('ge-0/0/0' in self.ppt)

    @patch('jnpr.junos.Device.execute')
    def test_table_items(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(len(self.ppt.items()[1][1]), 8)

    def test_table_get_return_none(self):
        self.assertEqual(self.table.get('ge-0/0/0'), None)

    def test_table_get_RuntimeError(self):
        self.assertRaises(RuntimeError, self.table._keys)

    @patch('jnpr.junos.Device.execute')
    @patch('__builtin__.file')
    def test_table_savexml(self, mock_file, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.xml = etree.XML('<root><a>test</a></root>')
        self.ppt.savexml('/vasr/tmssp/foo.xml', hostname=True, append='test')
        mock_file.assert_called_once_with('/vasr/tmssp/foo_1.1.1.1_test.xml',
                                          'w')
        self.ppt.savexml('/vasr/tmssp/foo.xml', hostname=True, timestamp=True)
        self.assertEqual(mock_file.call_count, 2)

    def _read_file(self, fname):
        from ncclient.xml_ import NCElement

        fpath = os.path.join(os.path.dirname(__file__),
                             'rpc-reply', fname)
        foo = open(fpath).read()

        rpc_reply = NCElement(foo, self.dev._conn.
                              _device_handler.transform_reply())\
            ._NCElement__doc[0]
        return rpc_reply

    def _mock_manager(self, *args, **kwargs):
        if kwargs:
            if 'normalize' in kwargs and args:
                return self._read_file(args[0].tag + '.xml')
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)

        if args:
            return self._read_file(args[0].tag + '.xml')
Ejemplo n.º 13
0
# Rick Mur - Juniper - 2015

from jnpr.junos import Device
from jnpr.junos.op.lldp import LLDPNeighborTable
import yaml
from pprint import pprint as pp

myVars = yaml.load(open("switchlist.yml").read())

for switch in myVars["switches"]:
    dev = Device(switch, user="******", password="******")
    dev.open()

    neighbors = LLDPNeighborTable(dev)
    neighbors.get()

    print ("Connected to " + dev.hostname)
    if len(neighbors) != 0:
        for neighbor in neighbors:
            print ("Interface " + neighbor.local_int + " is connecting to " + neighbor.remote_sysname)
    else:
        print ("No neighbors")

Ejemplo n.º 14
0
print("------LLDP------")

# Some advanced info requires Tables
# Tables are a PyEZ construct for retrieving
# more detailed information than basic facts.
# LLDPNeighborTable is built in to the library

# Loop through devices
for devname, device in devs.items():

    # Proper introductions
    print("Hi! I'm %s!" % devname)

    # Retrieve LLDP neighbors
    lldpneis = LLDPNeighborTable(device).get()

    # Loop over LLDP neighbors for this device
    for lldpnei in lldpneis:
        print('I see that %s is connected to my %s interface.' %
              (lldpnei.remote_sysname, lldpnei.key))

print("------BGP------")

# If your table is not built in to PyEZ, you can build your own!
# See bgpneighbor.yml, referenced below
# Also look at the "display xml [rpc] JunOS command"
globals().update(loadyaml('bgpneighbor.yml'))

# Loop over devices
for devname, device in devs.items():
Ejemplo n.º 15
0
#
# USAGE:
# c:\Python27\IP_FABRIC\audit>lldp_neighbor_status.py
# ---------------------------------------------------------------------------------------------------------------

from jnpr.junos import Device
from jnpr.junos.op.lldp import LLDPNeighborTable
import yaml
from datetime import datetime

my_list_of_devices = open('tables_and_views/devices.yml').read()
my_list_of_switches = yaml.load(my_list_of_devices)

f = open("lldp_neighbors.txt", "a")
f.write("\n" + str(datetime.now()) + "\n")

for host in my_list_of_switches:
    switch = Device(host=host, user='******', password='******')
    switch.open()
    print "\nLLDP neighbors of device " + host + " (hostname is " + switch.facts[
        "hostname"] + "):"
    f.write("\nLLDP neighbors of device " + host + " (hostname is " +
            switch.facts["hostname"] + "):\n")
    lldp_neighbors = LLDPNeighborTable(switch)
    lldp_neighbors.get()
    for neighbor in lldp_neighbors:
        print "interface " + neighbor.local_int + " has this neighbor: " + neighbor.remote_sysname
        f.write("interface " + neighbor.local_int + " has this neighbor: " +
                neighbor.remote_sysname + "\n")
f.close()
Ejemplo n.º 16
0
class TestFactoryTable(unittest.TestCase):
    @patch('ncclient.manager.connect')
    def setUp(self, mock_connect):
        mock_connect.side_effect = self._mock_manager
        self.dev = Device(host='1.1.1.1',
                          user='******',
                          password='******',
                          gather_facts=False)
        self.device_handler = JunosDeviceHandler(device_params={
            'name': 'junos',
            'local': False
        })
        self.dev.open()
        self.table = Table(dev=self.dev)
        self.ppt = PhyPortTable(self.dev)

    def test_config_constructor(self):
        self.assertTrue(isinstance(self.table.D, Device))

    def test_table_hostname(self):
        self.assertEqual(self.table.hostname, '1.1.1.1')

    def test_table_is_container(self):
        self.assertTrue(self.table.is_container)

    def test_table_repr_xml_none(self):
        self.assertEqual(repr(self.table), 'Table:1.1.1.1 - Table empty')

    def test_table_view_setter_ValueError(self):
        try:
            self.table.view = 'test'
        except Exception as ex:
            self.assertEqual(ex.__class__, ValueError)

    @patch('jnpr.junos.Device.execute')
    def test_keys_RuntimeError(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.ppt.ITEM_NAME_XPATH = 1
        self.assertRaises(RuntimeError, self.ppt.keys)

    @patch('jnpr.junos.Device.execute')
    def test_keys__keys_composite(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.ppt.ITEM_NAME_XPATH = ['name', 'missing', 'mtu']
        self.assertEqual(self.ppt.keys(), [('ge-0/0/0', None, '1514'),
                                           ('ge-0/0/1', None, '1514')])

    @patch('jnpr.junos.Device.execute')
    def test_keys__keys_pipe(self, mock_execute):
        from jnpr.junos.op.lldp import LLDPNeighborTable
        mock_execute.side_effect = self._mock_manager
        self.lldp = LLDPNeighborTable(self.dev)
        self.lldp.get()
        self.assertEqual(self.lldp.keys(),
                         ['et-0/0/48', 'et-0/0/49', 'xe-0/0/13'])

    @patch('jnpr.junos.Device.execute')
    def test_table_repr_xml_not_none(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.table.xml = self.ppt.xml
        self.table.ITEM_XPATH = self.ppt.ITEM_XPATH
        self.assertEqual(repr(self.table), 'Table:1.1.1.1: 2 items')

    @patch('jnpr.junos.Device.execute')
    def test_table_get_keys_values(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(self.ppt.keys(), ['ge-0/0/0', 'ge-0/0/1'])
        self.assertEqual(len(self.ppt.values()), 2)
        self.ppt.view = None
        self.assertEqual(len(self.ppt.values()), 2)

    @patch('jnpr.junos.Device.execute')
    def test_table__getitem__(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(self.ppt[0].ITEM_NAME_XPATH, 'name')

    @patch('jnpr.junos.Device.execute')
    def test_table__getitem__slice(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(self.ppt[:1][0].__class__.__name__, 'PhyPortView')

    @patch('jnpr.junos.Device.execute')
    def test_table__getitem__tuple(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertEqual(self.ppt[('ge-0/0/0', )], None)

    @patch('jnpr.junos.Device.execute')
    def test_table__contains__(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        self.assertTrue('ge-0/0/0' in self.ppt)

    @patch('jnpr.junos.Device.execute')
    def test_table_items(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get('ge-0/0/0')
        print(self.ppt.items())
        self.assertEqual(len(self.ppt.items()[1][1]), 8)

    def test_table_get_return_none(self):
        self.assertEqual(self.table.get('ge-0/0/0'), None)

    def test_table_get_RuntimeError(self):
        self.assertRaises(RuntimeError, self.table._keys)

    @patch('jnpr.junos.Device.execute')
    @patch(builtin_string + '.open')
    def test_table_savexml(self, mock_file, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.xml = etree.XML('<root><a>test</a></root>')
        self.ppt.savexml('/vasr/tmssp/foo.xml', hostname=True, append='test')
        mock_file.assert_called_once_with('/vasr/tmssp/foo_1.1.1.1_test.xml',
                                          'wb')
        self.ppt.savexml('/vasr/tmssp/foo.xml', hostname=True, timestamp=True)
        self.assertEqual(mock_file.call_count, 2)

    def _read_file(self, fname):
        from ncclient.xml_ import NCElement

        fpath = os.path.join(os.path.dirname(__file__), 'rpc-reply', fname)
        foo = open(fpath).read()

        rpc_reply = NCElement(foo, self.device_handler.transform_reply())\
            ._NCElement__doc[0]
        return rpc_reply

    def _mock_manager(self, *args, **kwargs):
        if kwargs:
            if args and ('normalize' in kwargs or 'filter_xml' in kwargs):
                return self._read_file(args[0].tag + '.xml')
            device_params = kwargs['device_params']
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)

        if args:
            return self._read_file(args[0].tag + '.xml')
Ejemplo n.º 17
0
# Rick Mur - Juniper - 2015

from jnpr.junos import Device
from jnpr.junos.op.lldp import LLDPNeighborTable
import yaml
from pprint import pprint as pp

myVars = yaml.load(open("switchlist.yml").read())

for switch in myVars["switches"]:
    dev = Device(switch, user="******", password="******")
    dev.open()

    neighbors = LLDPNeighborTable(dev)
    neighbors.get()

    print("Connected to " + dev.hostname)
    if len(neighbors) != 0:
        for neighbor in neighbors:
            print("Interface " + neighbor.local_int + " is connecting to " +
                  neighbor.remote_sysname)
    else:
        print("No neighbors")
from jnpr.junos import Device
from jnpr.junos.op.lldp import LLDPNeighborTable

port_list = ["2221", "2222", "2223"]

for item in port_list:
    dev = Device(host="127.0.0.1", user="******", password="******", port=item)
    dev.open()
    lldp_neighbors = LLDPNeighborTable(dev)
    lldp_neighbors.get()
    print "\nstatus of LLDP neighbors of " + dev.facts["hostname"] + ":"
    for xxx in lldp_neighbors:
        print "interface " + xxx.local_int + " has this neighbor: " + xxx.remote_sysname
    dev.close()
Ejemplo n.º 19
0
a_device = Device(**juniper_srx)
a_device.open()

eth_ports = EthPortTable(a_device)
eth_ports.get()
print '-' * 80
print "Ethernet Ports"
for k, v in eth_ports.items():
    juniper_print(k, v)
print '-' * 80
raw_input("Hit enter to continue: ")

arp = ArpTable(a_device)
arp.get()
print '-' * 80
print "ARP"
for k, v in arp.items():
    juniper_print(k, v)
print '-' * 80
raw_input("Hit enter to continue: ")

lldp = LLDPNeighborTable(a_device)
lldp.get()
print '-' * 80
print "LLDP Neighbors"
for k, v in lldp.items():
    juniper_print(k, v)
print '-' * 80
raw_input("Hit enter to continue: ")
print '-' * 80
 def lldp(self):
     if not hasattr(self, '_lldp'):
         self._lldp = LLDPNeighborTable(self.dev)
     return self._lldp.get()
Ejemplo n.º 21
0
class TestFactoryTable(unittest.TestCase):
    @patch("ncclient.manager.connect")
    def setUp(self, mock_connect):
        mock_connect.side_effect = self._mock_manager
        self.dev = Device(host="1.1.1.1",
                          user="******",
                          password="******",
                          gather_facts=False)
        self.device_handler = JunosDeviceHandler(device_params={
            "name": "junos",
            "local": False
        })
        self.dev.open()
        self.table = Table(dev=self.dev)
        self.ppt = PhyPortTable(self.dev)

    def test_config_constructor(self):
        self.assertTrue(isinstance(self.table.D, Device))

    def test_table_hostname(self):
        self.assertEqual(self.table.hostname, "1.1.1.1")

    def test_table_is_container(self):
        self.assertTrue(self.table.is_container)

    def test_table_repr_xml_none(self):
        self.assertEqual(repr(self.table), "Table:1.1.1.1 - Table empty")

    def test_table_view_setter_ValueError(self):
        try:
            self.table.view = "test"
        except Exception as ex:
            self.assertEqual(ex.__class__, ValueError)

    @patch("jnpr.junos.Device.execute")
    def test_keys_RuntimeError(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.ppt.ITEM_NAME_XPATH = 1
        self.assertRaises(RuntimeError, self.ppt.keys)

    @patch("jnpr.junos.Device.execute")
    def test_keys__keys_composite(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.ppt.ITEM_NAME_XPATH = ["name", "missing", "mtu"]
        self.assertEqual(self.ppt.keys(), [("ge-0/0/0", None, "1514"),
                                           ("ge-0/0/1", None, "1514")])

    @patch("jnpr.junos.Device.execute")
    def test_keys__keys_pipe(self, mock_execute):
        from jnpr.junos.op.lldp import LLDPNeighborTable

        mock_execute.side_effect = self._mock_manager
        self.lldp = LLDPNeighborTable(self.dev)
        self.lldp.get()
        self.assertEqual(self.lldp.keys(),
                         ["et-0/0/48", "et-0/0/49", "xe-0/0/13"])

    @patch("jnpr.junos.Device.execute")
    def test_table_repr_xml_not_none(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.table.xml = self.ppt.xml
        self.table.ITEM_XPATH = self.ppt.ITEM_XPATH
        self.assertEqual(repr(self.table), "Table:1.1.1.1: 2 items")

    @patch("jnpr.junos.Device.execute")
    def test_table_get_keys_values(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.assertEqual(self.ppt.keys(), ["ge-0/0/0", "ge-0/0/1"])
        self.assertEqual(len(self.ppt.values()), 2)
        self.ppt.view = None
        self.assertEqual(len(self.ppt.values()), 2)

    @patch("jnpr.junos.Device.execute")
    def test_table__getitem__(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.assertEqual(self.ppt[0].ITEM_NAME_XPATH, "name")

    @patch("jnpr.junos.Device.execute")
    def test_table__getitem__slice(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.assertEqual(self.ppt[:1][0].__class__.__name__, "PhyPortView")

    @patch("jnpr.junos.Device.execute")
    def test_table__getitem__tuple(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.assertEqual(self.ppt[("ge-0/0/0", )], None)

    @patch("jnpr.junos.Device.execute")
    def test_table__contains__(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.assertTrue("ge-0/0/0" in self.ppt)

    @patch("jnpr.junos.Device.execute")
    def test_table_items(self, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.get("ge-0/0/0")
        self.assertEqual(len(self.ppt.items()[1][1]), 8)

    def test_table_get_return_none(self):
        self.assertEqual(self.table.get("ge-0/0/0"), None)

    def test_table_get_RuntimeError(self):
        self.assertRaises(RuntimeError, self.table._keys)

    @patch("jnpr.junos.Device.execute")
    @patch(builtin_string + ".open")
    def test_table_savexml(self, mock_file, mock_execute):
        mock_execute.side_effect = self._mock_manager
        self.ppt.xml = etree.XML("<root><a>test</a></root>")
        self.ppt.savexml("/vasr/tmssp/foo.xml", hostname=True, append="test")
        mock_file.assert_called_once_with("/vasr/tmssp/foo_1.1.1.1_test.xml",
                                          "wb")
        self.ppt.savexml("/vasr/tmssp/foo.xml", hostname=True, timestamp=True)
        self.assertEqual(mock_file.call_count, 2)

    def _read_file(self, fname):
        from ncclient.xml_ import NCElement

        fpath = os.path.join(os.path.dirname(__file__), "rpc-reply", fname)
        foo = open(fpath).read()

        rpc_reply = NCElement(
            foo, self.device_handler.transform_reply())._NCElement__doc[0]
        return rpc_reply

    def _mock_manager(self, *args, **kwargs):
        if kwargs:
            if args and ("normalize" in kwargs or "filter_xml" in kwargs):
                return self._read_file(args[0].tag + ".xml")
            device_params = kwargs["device_params"]
            device_handler = make_device_handler(device_params)
            session = SSHSession(device_handler)
            return Manager(session, device_handler)

        if args:
            return self._read_file(args[0].tag + ".xml")
Ejemplo n.º 22
0
 def test_table_union(self):
     lldp = LLDPNeighborTable(self.dev)
     lldp.get('et-0/1/1')
     self.assertEqual(lldp['et-0/1/1'].local_int, 'et-0/1/1')
Ejemplo n.º 23
0
 def test_table_union(self):
     lldp = LLDPNeighborTable(self.dev)
     lldp.get('et-0/1/1')
     self.assertEqual(lldp['et-0/1/1'].local_int, 'et-0/1/1')