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)
Example #2
0
 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)
Example #3
0
 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 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)
Example #5
0
def print_interface_table(hostname):
    dev = Device(user=username, host=hostname, password=password, gather_facts=False, normalize=True)
    dev.open()
    port_table = PhyPortTable(dev).get()
    for port in port_table:
        print hostname, port.name, port.macaddr, port.flapped
    dev.close()
Example #6
0
def get_interfaces(args):
    """
    Connect to device over NETCONF protocol and obtain list of interfaces.
    This uses jnpr.junos.op.phyport.PhyPortTable
    """

    dev = Device(host=args['hostname'], user=args['user'],
                 ssh_private_key_file=args['sshkey'],
                 ssh_config=args['sshconfig'])

    try:
        dev.open()
    except:
        print('Unexpected error with NETCONF connection.  Try `ssh ' +
              args['hostname'] + '`')
        exit(3)

    interfaces = PhyPortTable(dev).get()
    dev.close()

    return interfaces
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')
from pprint import pprint
from jnpr.junos import Device
from jnpr.junos.op.phyport import PhyPortTable

with Device(host='34.208.13.114',
            user='******',
            password='******',
            gather_facts=False) as dev:
    intf_status = PhyPortTable(dev)
    intf_status.get()
    for intf in intf_status:
        if intf.oper == 'up':
            print(
                f"Interface {intf.name} is up and has MAC address {intf.macaddr}"
            )
Example #9
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')
Example #10
0
ports['fe-0/0/1']['oper']
ports['fe-0/0/1']['macaddr']



from jnpr.junos.op.arp import ArpTable
arp_entries = ArpTable(a_device)
arp_entries.get()
arp_entries.items()
arp_entries.keys()
arp_entries.values()


from jnpr.junos.op.phyport import PhyPortTable
phy_ports = PhyPortTable(a_device)
phy_ports.get()
phy_ports.items()
phy_ports.keys()
phy_ports.values()
phy_ports['fe-0/0/1']
phy_ports['fe-0/0/1'].keys()
phy_ports['fe-0/0/1'].items()


from jnpr.junos.op.phyport import PhyPortStatsTable
port_stats = PhyPortStatsTable(a_device)
port_stats.get()
port_stats.keys()
port_stats['fe-0/0/1'].items()
Example #11
0
#pynet-sf-srx ansible_ssh_host=184.105.247.76 juniper_user=pyclass juniper_passwd=88newclass
from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from jnpr.junos.op.arp import ArpTable
from jnpr.junos.op.phyport import PhyPortTable
from jnpr.junos.op.phyport import PhyPortStatsTable
from getpass import getpass
from pprint import pprint

a_device = Device(host='184.105.247.76', user='******', password='******')
a_device.open()
ports = EthPortTable(a_device)
jports=ports.get()
pprint(jports)
#pprint(jports['fe-0/0/1'].items())
phy_ports = PhyPortTable(a_device)
pp = phy_ports.get() 
print "PP type %s" %type(pp)
p = pp.items()
for key,values in p:
    print key 
    for k,v in values:
        print "  %s %s" %(k,v)

port_stats = PhyPortStatsTable(a_device)
ps = port_stats.get()
p = ps.items()
for key,values in p:
    print key
    for k,v in values:
        print "  %s %s" %(k,v)
Example #12
0
import sys
from jnpr.junos import Device
from jnpr.junos.exception import *
from jnpr.junos.op.routes import RouteTable
from jnpr.junos.op.phyport import PhyPortTable
from pprint import pprint

junos_hosts = ['172.30.92.193']

for ip in junos_hosts:
    try:
        dev = Device(host=ip, user='******', password='******')
        dev.open()
        routes = RouteTable(dev)
        interfaces = PhyPortTable(dev)
        routes.get()
        #print(type(routes))
        # print(routes.get())
        # print(routes.keys())
        #
        # print the interface list
        # print(interfaces.get())
        # print(type(interfaces.keys()))
        # print(interfaces.keys()[0])
        #
        for route in routes.keys():
            if routes[route]['protocol'] == 'local':
                print(route)
            else:
                #print(route)
                pass
Example #13
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")