Esempio n. 1
0
    def collectBgpFromDevice(self):
        logger.debug('Start BGP data collector for %s' % (self.deviceLogStr))

        try:
            bgpTable = loadyaml(os.path.join(junosEzTableLocation, 'BGP.yaml'))['BGPNeighborTable']
            table = bgpTable(self.deviceConnectionHandle)
            bgpData = table.get()
            links = []
            for link in bgpData:
                device1Name = self.device.name
                # strip ip
                device1Ip = util.stripPlusSignFromIpString(link.local_add)
                device2Ip = util.stripPlusSignFromIpString(link.peer_add)
                # find device2's hostname by AS
                device2Asn = int(link.peer_as)
                device2Obj = self.deviceAsn2NameMap.get(device2Asn)
                if device2Obj is not None:
                    device2Name = device2Obj.name
                else:
                    logger.debug('Cannot find device2 by AS %d' % device2Asn)
                    device2Name = None
                    
                logger.debug('device1: %s, device1Ip: %s, device1as1: %s, device2: %s, device2Ip: %s, device2as: %s, inputMsgCount: %s, outputMsgCount: %s, outQueueCount: %s , linkState : %s, active/receive/acceptCount: %s/%s/%s, flapCount : %s' % (device1Name, device1Ip, link.local_as, device2Name, device2Ip, link.peer_as, link.in_msg, link.out_msg, link.out_queue, link.state, link.act_count, link.rx_count, link.acc_count, link.flap_count ) )
                links.append({'device1': device1Name, 'device1Ip': device1Ip , 'device1as': link.local_as, 'device2': device2Name, 'device2Ip': device2Ip, 'device2as': link.peer_as, 'inputMsgCount': link.in_msg,
                                  'outputMsgCount': link.out_msg, 'outQueueCount': link.out_queue , 'linkState' : link.state, 'activeReceiveAcceptCount': (str(link.act_count) +'/' + str(link.rx_count) + '/' + str(link.acc_count)), 'flapCount': link.flap_count, 'device2Obj': device2Obj})
                    
            logger.debug('End BGP data collector for %s' % (self.deviceLogStr))
            return links
        except RpcError as exc:
            logger.error('BGP data collection failure, %s' % (exc))
            raise DeviceRpcFailed("device '%s': BGPNeighborTable" % (self.deviceId), exc)
        except Exception as exc:
            logger.error('Unknown error, %s' % (exc))
            logger.debug('StackTrace: %s' % (traceback.format_exc()))
            raise DeviceRpcFailed("device '%s': BGPNeighborTable" % (self.deviceId), exc)
Esempio n. 2
0
def juniper_find_mac(dev, template, mac):
    '''
    This function is used to find a specific mac address on a Juniper network device.

    dev = Juniper device connection
    template = YAML file
    mac = MAC address (Format: xx:xx:xx:xx:xx:xx)
    return = Returns the specific mac entry if found
    This function might not work on older versions of Junos.
    '''

    try:
        globals().update(loadyaml(template))

        mac_table = mac_table_info(dev).get(address=mac)

        if mac_table:
            for item in mac_table:
                if item.mac_address == mac:
                    return dict(item)
        else:
            print('\n' + "MAC NOT FOUND")
            sys.exit(1)

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
        return

    return
Esempio n. 3
0
def main():
    globals().update(loadyaml(yamlfile))
    hosts = config.get('hosts')

    for host in hosts:
        dev = Device(host=host, user=user, password=password)
        try:
            dev.open()
        except Exception as err:
            print("Cannot connect to device: {}".format(err))
            return

        peerTable = BgpNeighborTable(dev)
        peerTable.get()
        for entry in peerTable:
            peer = dict(entry)
            print("Neighbor: {}:{}".format(peer["peer-address"],
                  peer["peer-as"]))
            print("    Description: {}".format(peer["description"]))
            print("    State: {}".format(peer["peer-state"]))
            print("    RIB: {}".format(peer["rib-name"]))
            print("    Stats:")
            print("        Accepted Prefixes: {}"
                  .format(peer["accepted-prefix"]))
            print("        Suppressed Prefixes: ",
                  "{}".format(peer["suppressed-prefix"]))
            print("        Active Prefixes: {}".format(peer["active-prefix"]))
            print("        Received Prefixes: {}"
                  .format(peer["received-prefix"]))
            print()

        dev.close()
Esempio n. 4
0
    def runTest(self):
        globals().update(loadyaml('bgpneighbor.yml'))

        bgpneighbors = BGPNeighborTable(self.dev).get()

        for bgpnei in bgpneighbors:
            self.assertEqual(int(bgpnei.pfx_rx), 1)
Esempio n. 5
0
def main():
    globals().update(loadyaml(yamlfile))
    hosts = config.get('hosts')

    for host in hosts:
        dev = Device(host=host, user=user, password=password)
        try:
            dev.open()
        except Exception as err:
            print("Cannot connect to device: {}".format(err))
            return

        peerTable = BgpNeighborTable(dev)
        peerTable.get()
        for entry in peerTable:
            peer = dict(entry)
            print("Neighbor: {}:{}".format(peer["peer-address"],
                                           peer["peer-as"]))
            print("    Description: {}".format(peer["description"]))
            print("    State: {}".format(peer["peer-state"]))
            print("    RIB: {}".format(peer["rib-name"]))
            print("    Stats:")
            print("        Accepted Prefixes: {}".format(
                peer["accepted-prefix"]))
            print("        Suppressed Prefixes: ",
                  "{}".format(peer["suppressed-prefix"]))
            print("        Active Prefixes: {}".format(peer["active-prefix"]))
            print("        Received Prefixes: {}".format(
                peer["received-prefix"]))
            print()

        dev.close()
Esempio n. 6
0
    def collectLldpFromDevice(self):
        logger.debug('Start LLDP data collector for %s' % (self.deviceLogStr))

        try:
            lldpTable = loadyaml(
                os.path.join(junosEzTableLocation,
                             'lldp.yaml'))['LLDPNeighborTable']
            table = lldpTable(self.deviceConnectionHandle)
            lldpData = table.get()
            links = {}
            for link in lldpData:
                logger.debug(
                    'device1: %s, port1: %s, device2: %s, port2: %s' %
                    (link.device1, link.port1, link.device2, link.port2))
                links[link.port1] = {
                    'device1': link.device1,
                    'port1': link.port1,
                    'device2': link.device2,
                    'port2': link.port2
                }

            logger.debug('End LLDP data collector for %s' %
                         (self.deviceLogStr))
            return links
        except RpcError as exc:
            logger.error('LLDP data collection failure, %s' % (exc))
            raise DeviceRpcFailed(
                "device '%s': LLDPNeighborTable" % (self.deviceId), exc)
        except Exception as exc:
            logger.error('Unknown error, %s' % (exc))
            logger.debug('StackTrace: %s' % (traceback.format_exc()))
            raise DeviceRpcFailed(
                "device '%s': LLDPNeighborTable" % (self.deviceId), exc)
Esempio n. 7
0
def main():
    globals().update(loadyaml(yamlfile))
    dev = Device(host=host, user=user, password=password)
    try:
        dev.open()
    except Exception as err:
        print "Cannot connect to device:", err
        return

    peerTable = BgpNeighborTable(dev)
    peerTable.get()
    for entry in peerTable:
        # print peer.items()
        # print "-----"
        # print
        peer = dict(entry)
        print "Neighbor: {}:{}".format(peer["peer-address"], peer["peer-as"])
        print "    Description: {}".format(peer["description"])
        print "    State: {}".format(peer["peer-state"])
        print "    RIB: {}".format(peer["rib-name"])
        print "    Stats:"
        print "        Accepted Prefixes: {}".format(peer["accepted-prefix"])
        print "        Suppressed Prefixes: " \
            "{}".format(peer["suppressed-prefix"])
        print "        Active Prefixes: {}".format(peer["active-prefix"])
        print "        Received Prefixes: {}".format(peer["received-prefix"])
        print

    dev.close()
Esempio n. 8
0
def get_fpc_yml(dev):
	fpcs_xpath=dev.rpc.get_fpc_information()
	pprint(etree.dump(fpcs_xpath))
	user_defs=loadyaml('UserFPCTable.yml')
	globals().update(user_defs)
	user_table=UserFPCTable(dev)
	user_table.get()
	pprint(user_table.items())
Esempio n. 9
0
 def __init__(self, name, address, un, passw):
     self.yml_file = "routeStatus.yml"
     globals().update(loadyaml(self.yml_file))
     self.dev = Device(host=address, user=un, passwd=passw)
     self.name = name
     self.version = ''
     self.lastState = False
     self.lastError = ''
Esempio n. 10
0
    def __init__(self, name, address, un, passw):
        self.yml_file = "routeStatus.yml"
        globals().update(loadyaml(self.yml_file))
        self.dev = Device(host=address, user=un, passwd=passw)
        self.name = name
        self.version = ''
        self.address = address

        self.param = os.getpid()
        self.param2 = 0
Esempio n. 11
0
def get_vlan_dict(dev, strict=0):
    globals().update(loadyaml('templates/vlans.yaml'))
    vlans = VlanTable(dev)
    vlans.get()
    vlans_keys = vlans.keys()
    vlans_values = vlans.values()
    if strict == 0:
        return {k: v for k, v in zip(vlans_keys, vlans_values)}
    else:
        return {
            k: v
            for k, v in zip(vlans_keys, vlans_values)
            if k == parser.parse_args().vlan[0]
        }
Esempio n. 12
0
def main():
    globals().update(loadyaml(yamlfile))
    dev = Device(host=host, user=user, password=password)
    try:
        dev.open()
    except Exception as err:
        print "Cannot connect to device:", err
        return

    peerTable = BgpNeighborTable(dev)
    peerTable.get()
    for entry in peerTable:
        print entry.items()
        print "-----"
        print

    dev.close()
Esempio n. 13
0
def juniper_arp_table(dev):
    """
    This function queries the ARP table on a Juniper network device.

    dev = Juniper device connection
    return = Returns ARP table
    """

    try:
        template = 'yaml/arp_table_def.yml'
        globals().update(loadyaml(template))
        arp_table = arp_table_info(dev).get(no_resolve=True)

        return arp_table

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
Esempio n. 14
0
def main():
    globals().update(loadyaml(yamlfile))
    hosts = config.get('hosts')

    for host in hosts:
        dev = Device(host=host, user=user, password=password)
        try:
            dev.open()
        except Exception as err:
            print("Cannot connect to device: {}".format(err))
            return

        peerTable = BgpNeighborTable(dev)
        peerTable.get()
        for entry in peerTable:
            print(entry.items())
            print("-----")
            print()

        dev.close()
Esempio n. 15
0
    def collectLldpFromDevice(self):
        logger.debug('Start LLDP data collector for %s' % (self.deviceLogStr))

        try:
            lldpTable = loadyaml(os.path.join(junosEzTableLocation, 'lldp.yaml'))['LLDPNeighborTable'] 
            table = lldpTable(self.deviceConnectionHandle)
            lldpData = table.get()
            links = {}
            for link in lldpData:
                logger.debug('device1: %s, port1: %s, device2: %s, port2: %s' % (link.device1, link.port1, link.device2, link.port2))
                links[link.port1] = {'device1': link.device1, 'port1': link.port1, 'device2': link.device2, 'port2': link.port2}
                
            logger.debug('End LLDP data collector for %s' % (self.deviceLogStr))
            return links
        except RpcError as exc:
            logger.error('LLDP data collection failure, %s' % (exc))
            raise DeviceRpcFailed("device '%s': LLDPNeighborTable" % (self.deviceId), exc)
        except Exception as exc:
            logger.error('Unknown error, %s' % (exc))
            logger.debug('StackTrace: %s' % (traceback.format_exc()))
            raise DeviceRpcFailed("device '%s': LLDPNeighborTable" % (self.deviceId), exc)
Esempio n. 16
0
def juniper_lldp_neighbor(dev):
    """
    This function is used to gather LLDP data from a Juniper network device.

    dev = Juniper device connection
    return = Returns the LLDP neighbor table
    """

    try:
        globals().update(loadyaml('yaml/lldp_neighbor.yml'))
        lldp_ni = lldp_neighbor_info(dev).get()

        return lldp_ni

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
        return

    return
Esempio n. 17
0
def juniper_int_terse(dev):
    """
    This function is used to get show interface terse data from a Juniper network device.

    dev = Juniper device connection
    return = Returns the show interface terse table for ge- and xe- interfaces
    """
    try:
        globals().update(loadyaml('yaml/junos_interface.yml'))
        interface_terse = junos_logical_interface_general_terse(dev).get(
            terse=True, interface_name='[g,x,f]*')

        return interface_terse

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
        return

    return
Esempio n. 18
0
def juniper_bgp_state(dev, bgp_neighbor):
    """
    This function queries the BGP neighbor table on a Juniper network device.

    dev = Juniper device connection
    bgp_neighbor = IP address of BGP neighbor
    return = Returns state of BGP neighbor
    """
    try:
        globals().update(loadyaml('yaml/bgp_neighbor.yml'))
        bgp_ni = bgp_neighbor_info(dev).get(neighbor_address=bgp_neighbor)

        return bgp_ni

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
        return

    return
Esempio n. 19
0
def juniper_find_arp(dev, ip):
    """
    This function queries the ARP table on a Juniper network device looking for a specific MAC address.

    dev = Juniper device connection
    ip = IP address
    return = Returns ARP information for specified IP address
    """

    try:
        template = 'yaml/arp_table_def.yml'
        globals().update(loadyaml(template))
        arp_table = arp_table_info(dev).get(no_resolve=True)

        for item in arp_table:
            if item.ip_address == ip:
                return dict(item)

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
Esempio n. 20
0
def juniper_bgp_summary(dev):
    """
    This function queries BGP summary information on a Juniper network device.

    dev = Juniper device connection
    return = Returns BGP summary information
    """

    try:
        globals().update(loadyaml('yaml/bgp_summary.yml'))

        bgp_summary = bgp_summary_info(dev).get()

        return bgp_summary

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
        return

    return
Esempio n. 21
0
def juniper_mac_table(dev, template):
    """
    This function is used to query the mac table on a Juniper network device.

    dev = Juniper device connection
    template = YAML file
    mac = MAC address (Format: xx:xx:xx:xx:xx:xx)
    return = Returns the complete mac table
    """

    try:
        globals().update(loadyaml(template))
        mac_table = mac_table_info(dev).get()

        return mac_table

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
        return

    return
Esempio n. 22
0
def juniper_int_terse_exact(dev, interface_num):
    '''
    This function is used to get information about a specific interface.

    dev = Juniper device connection
	interface_num = Interface - format ge-0/0/1
    return = Returns information about the interface
    '''

    try:
        globals().update(loadyaml('yaml/junos_interface.yml'))
        interface_terse = junos_logical_interface_terse(dev).get(
            terse=True, interface_name=interface_num)

        return interface_terse

    except Exception as err:
        print(err)
        dev.close()
        sys.exit(1)
        return

    return
Esempio n. 23
0
Author: Dan Houtz
Email: [email protected]

'''

from multiprocessing import Pool
from jnpr.junos import Device
from jnpr.junos.factory import loadyaml
import logging

#Disable logging handler warnings
logging.root.manager.emittedNoHandlerWarning = True

#Load license TABLE/VIEW data from yaml file
globals().update( loadyaml('license'))

# Default variables
failed_check = []

#Set number of worker threads
maxThreads=10

#Array of devices to check
device_list = []

#SSH username/password to connect to devices
user = ''
password = ''

#Array of devices to ignore during processing
Esempio n. 24
0
    def collectBgpFromDevice(self):
        logger.debug('Start BGP data collector for %s' % (self.deviceLogStr))

        try:
            bgpTable = loadyaml(os.path.join(junosEzTableLocation,
                                             'BGP.yaml'))['BGPNeighborTable']
            table = bgpTable(self.deviceConnectionHandle)
            bgpData = table.get()
            links = []
            for link in bgpData:
                device1Name = self.device.name
                # strip ip
                device1Ip = util.stripPlusSignFromIpString(link.local_add)
                device2Ip = util.stripPlusSignFromIpString(link.peer_add)
                # find device2's hostname by AS
                device2Asn = int(link.peer_as)
                device2Obj = self.deviceAsn2NameMap.get(device2Asn)
                if device2Obj is not None:
                    device2Name = device2Obj.name
                else:
                    logger.debug('Cannot find device2 by AS %d' % device2Asn)
                    device2Name = None

                logger.debug(
                    'device1: %s, device1Ip: %s, device1as1: %s, device2: %s, device2Ip: %s, device2as: %s, inputMsgCount: %s, outputMsgCount: %s, outQueueCount: %s , linkState : %s, active/receive/acceptCount: %s/%s/%s, flapCount : %s'
                    % (device1Name, device1Ip, link.local_as, device2Name,
                       device2Ip, link.peer_as, link.in_msg, link.out_msg,
                       link.out_queue, link.state, link.act_count,
                       link.rx_count, link.acc_count, link.flap_count))
                links.append({
                    'device1':
                    device1Name,
                    'device1Ip':
                    device1Ip,
                    'device1as':
                    link.local_as,
                    'device2':
                    device2Name,
                    'device2Ip':
                    device2Ip,
                    'device2as':
                    link.peer_as,
                    'inputMsgCount':
                    link.in_msg,
                    'outputMsgCount':
                    link.out_msg,
                    'outQueueCount':
                    link.out_queue,
                    'linkState':
                    link.state,
                    'activeReceiveAcceptCount':
                    (str(link.act_count) + '/' + str(link.rx_count) + '/' +
                     str(link.acc_count)),
                    'flapCount':
                    link.flap_count,
                    'device2Obj':
                    device2Obj
                })

            logger.debug('End BGP data collector for %s' % (self.deviceLogStr))
            return links
        except RpcError as exc:
            logger.error('BGP data collection failure, %s' % (exc))
            raise DeviceRpcFailed(
                "device '%s': BGPNeighborTable" % (self.deviceId), exc)
        except Exception as exc:
            logger.error('Unknown error, %s' % (exc))
            logger.debug('StackTrace: %s' % (traceback.format_exc()))
            raise DeviceRpcFailed(
                "device '%s': BGPNeighborTable" % (self.deviceId), exc)
#!/usr/bin/python

from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.factory import loadyaml

from getpass import getpass
host = raw_input('hostname or address: ')
username = raw_input('username: '******'password: '******'vlaninfo.yml'))

dev = Device(host, user=username, password=passwd)

dev.open()
dev.timeout = 60

formatter = "{0:<14}{1:<14}{2:<17}{3:<8}{4:<30}"
header = formatter.format("Name", "L3 Int", "L3 Address", "Count", "Member List")
print header

vlan_table = ShowInterface(dev)
vlan_table.get()

for i in vlan_table:
    memberlist = formatter.format(str(i.name), str(i.l3int), str(i.l3addr), str(i.membercount), str(i.memberlist))
    print memberlist

dev.close()
Esempio n. 26
0
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
log.basicConfig(filename="net_to_db.log",
                format='%(asctime)s - %(levelname)s - %(message)s',
                level=getattr(log, LOG_LEVEL))
console = log.StreamHandler()
console.setLevel(getattr(log, LOG_LEVEL))
formatter = log.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
log.getLogger('').addHandler(console)

for fileName in yamlTBL_to_MongoCollections:
    # Adding path and '.yml' extension
    file = PATH_TO_YAML + fileName + '.yml'
    try:
        globals().update(FactoryLoader.loadyaml(file))
    except IOError as err:
        log.error('error: failed to load: ' + file + '...' + repr(err) +
                  '. Skipping...')
        continue
    else:
        log.info('Succesfully loaded: ' + file + '...')

# trying to connect to MongoDB using mongo Driver
try:
    dbclient = MongoClient('localhost', 27017)
except pymongo.errors.ServerSelectionTimeoutError as err:
    log.critical("ERROR: failed to connect to DB (" + repr(err) + ")")
    log.critical("ERROR: Exiting....")
    exit(1)
Esempio n. 27
0
import jnpr.junos.exception
from jexceptions import jException
from jnpr.junos import Device
from pprint import pprint as pp
from decimal import *
import multiprocessing as mp
# import yaml
# from jnpr.junos.factory.factory_loader import FactoryLoader
from jnpr.junos.factory import loadyaml
from termcolor import colored
from IPy import IP

SUCCESSFUL = 0
CONNECTION_FAILED = 1

TABLE_DEFS = loadyaml('jvision.yml')
globals().update(TABLE_DEFS)


class myDev():

    def __init__(self, hostname=None, port=None, username=None, password=None):
        self.hostname = hostname
        self.port = port
        self.username = username
        self.password = password
        self.jnprdev = Device(host=hostname,
                              username=username,
                              password=password,
                              port=port,
                              timeout=5,
Esempio n. 28
0
from jnpr.junos.factory import loadyaml
from jnpr.junos import Device

globals().update( loadyaml('/root/pyez/bgp_table.yml'))
dev = Device(host='172.2.3.5',user='******',ssh_private_key_file='/root/.ssh/VRF')
dev.open()
tbl=BgpNeigh(dev)
tbl.get()
for k in tbl:
   print k.items()
Esempio n. 29
0
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.factory import loadyaml

from getpass import getpass
host = raw_input('hostname or address: ')
username = raw_input('username: '******'password: '******'what source address pattern are you looking for? ')
appl = raw_input('what application port are you looking for [any]? ') or 'any'

globals().update(loadyaml('flowsession.yml'))

dev = Device(host, user=username, password=passwd)

dev.open()
dev.timeout = 60

session_table = SessionTable(dev)
session_table.get()

header = formatter.format("source", "destination", "destination port")
print "\n" + header

for s in session_table:
    if session_table.keys():
        if "any" in appl and s.session_protocol == 'tcp' and s.session_direction == 'In':
#!/usr/bin/python

from jnpr.junos import Device
from jnpr.junos.op.ethport import *
from jnpr.junos.factory import loadyaml
from pprint import pprint

#Loads the custom .yml file using the loadyaml function imported.  Manual way.
#mydefs = loadyaml('ethport.yml')
ospfNeighbors = loadyaml('yaml-definitions/ospfneighbors2.yml')
globals().update(ospfNeighbors)
 
ex2200 = Device(host='192.168.2.1',user='******',password='******')

eths = EthPortTable(ex2200)
ospfneighbors = OSPFNeighborTable(ex2200)

ex2200.open()


interface = "ge-0/0/0"


ospfneighbors.get()

# Example of if statements to determine certain things
print eths.get()
if  eths['ge-0/0/0'].oper == "up":
	print "ge-0/0/0 is up"
else:
	print "it's down"
Esempio n. 31
0
import os
from nose.plugins.attrib import attr
import yaml

from jnpr.junos import Device

from ncclient.manager import Manager, make_device_handler
from ncclient.transport import SSHSession
from lxml import etree
from mock import MagicMock, patch

from jnpr.junos.factory import loadyaml
from jnpr.junos.factory.factory_loader import FactoryLoader

try:
    _YAML_ = loadyaml('lib/jnpr/junos/cfgro/srx')
except:
    # Try to load the template relative to test base
    try:
        _YAML_ = loadyaml(
            os.path.join(os.path.dirname(__file__), '../../..',
                         'lib/jnpr/junos/cfgro/srx.yml'))
    except:
        raise

globals().update(_YAML_)

yaml_data = \
    """---
    UserTable:
      get: system/login/user
Esempio n. 32
0
    # 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():

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

    # Retrieve BGP Neighbors
    bgpneighbors = BGPNeighborTable(device).get()

    # Loop over BGP neighbors for this device
    for bgpnei in bgpneighbors:

        print('My BGP neighbor: %s from AS# %s has sent me %s prefixes.' % (
            bgpnei.peeraddr,
import os
from nose.plugins.attrib import attr
import yaml

from jnpr.junos import Device

from ncclient.manager import Manager, make_device_handler
from ncclient.transport import SSHSession
from lxml import etree
from mock import MagicMock, patch

from jnpr.junos.factory import loadyaml
from jnpr.junos.factory.factory_loader import FactoryLoader

try:
    _YAML_ = loadyaml('lib/jnpr/junos/cfgro/srx')
except:
    # Try to load the template relative to test base
    try:
        _YAML_ = loadyaml(os.path.join(os.path.dirname(__file__), '../../..',
                                       'lib/jnpr/junos/cfgro/srx.yml'))
    except:
        raise

globals().update(_YAML_)

yaml_data = \
    """---
    UserTable:
      get: system/login/user
      required_keys:
Esempio n. 34
0
from jnpr.junos.op.routes import RouteTable

dev = Device(
    host='127.0.0.1', user='******', password='******', port=sys.argv[1]
)

dev.open()

# Warning - this will break if you haven't applied the base configuration yet

lldpneis = LLDPNeighborTable(dev).get()

print("LLDP Neighbors: %s" % len(lldpneis))

scriptdir = os.path.dirname(os.path.realpath(__file__))

globals().update(loadyaml('%s/bgpneighbor.yml' % scriptdir))

bgpneighbors = BGPNeighborTable(dev).get()

print("BGP Neighbors: %s" % len(bgpneighbors))

route_table = RouteTable(dev)
routes = route_table.get('123.123.123.1/24')
if len(routes) == 1:
    print("Mission ACCOMPLISHED")
else:
    print("Mission NOT YET ACCOMPLISHED")

dev.close()
Esempio n. 35
0
#!/usr/bin/python

from pprint import pprint as pp
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.factory import loadyaml

dev = Device('10.9.5.201', user='******', password='******')

dev.open()
dev.timeout = 60

globals().update(loadyaml('partitioninfo-tfc.yml'))
partition_table = PartitionTable(dev)
partition_table.get()

pp(partition_table[0])
pp(partition_table[0].items())

pp(partition_table[1])
pp(partition_table[1].items())

#for s in partition_table:
#  if partition_table.keys():
#    pprint(partition_table.values())

dev.close()
if opts.returncode == 12:
    sys.exit(1)
'''
user name/password
'''
_usrname = opts.args.u
_password = opts.args.p
'''
locate the YAML file
'''
if opts.args.f is None:
    _yamlfile = './ospfoutput.yml'
else:
    _yamlfile = opts.args.f

globals().update(loadyaml(_yamlfile))
'''
define output format
'''
outfmt = "%16s%20s%10s%16s%16s%16s%10s"


def gen_sepline(count):
    '''
	Generating the sepration line
	eg:  ----------------
	'''
    line = '-'
    for x in range(count):
        line = line + '-'
    return line
Esempio n. 37
0
import numpy as np
import os.path

#Setup Variables
csv = 'csv/csv.csv'
userName = '******'
userPassword = '******'
save_path = 'output'
#save file name prefix
prefix = 'dev'

#Create 2D Array from csv [name,ip]
devList=np.genfromtxt(csv,delimiter=',',dtype=None)

#Setup Views
mydefs = loadyaml('yaml/allport.yml')
globals().update(mydefs)

def main():
	#Setup for output
	now = datetime.datetime.now()
	txt = os.path.join(save_path, "stats-" + prefix + "-" + now.strftime("%Y%m%d-%H%M") + ".txt")
	text_file =  open(txt, "w")
	text_file.write("+++++++++++++++++++++++++++++++++++++++++++++++++")
	text_file.write('\n')

	#iterate over csv
	for row in devList:

        	#define host for pyez
        	dev = Device(host=row[1], user=userName, password=userPassword)
Esempio n. 38
0
    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():

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

    # Retrieve BGP Neighbors
    bgpneighbors = BGPNeighborTable(device).get()

    # Loop over BGP neighbors for this device
    for bgpnei in bgpneighbors:

        print('My BGP neighbor: %s from AS# %s has sent me %s prefixes.' %
              (bgpnei.peeraddr, bgpnei.peeras, bgpnei.pfx_rx))
Esempio n. 39
0
#!/usr/bin/python

from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.factory import loadyaml

from getpass import getpass
host = raw_input('hostname or address: ')
username = raw_input('username: '******'password: '******'showinterface.yml'))

dev = Device(host, user=username, password=passwd)
#dev = Device(hostname, user=username, password=passwd)

dev.open()
dev.timeout = 60

interface_table = ShowInterface(dev)
interface_table.get()

for i in interface_table:
  if "ge" in i.name or "fe" in i.name or "vlan" in i.name:
    if i.addrfamily == 'inet' and i.status == 'up':
      print str(i.logicalname) +  " " + str(i.logicalinetaddr)
#      print i.name + " " + str(i.description) + " " + str(i.linkmode) + " " + str(i.linkspeed) + " " + str(i.logicalname) + " " + str(i.logicalinetaddr)

dev.close()
Esempio n. 40
0
#!/usr/bin/python
# RMZ 2014

import sys, math
from jnpr.junos.utils.config import Config
from jnpr.junos import Device
from jnpr.junos.factory import loadyaml

globals().update(loadyaml("bgp-peer.yml"))


dev = Device(host="cr-xx-01", user="******", password="******")
try:
    dev.open()
    results = BgpPeerTable(dev).get()
    cu = Config(dev)
except Exception as err:
    print err
    sys.exit(1)

for r in results:
    if r.peer_type == "External" and r.table == "inet.0" and r.policy != "none":
        neighbor, port = r.peer_address.split("+")
        ixt = r.policy.split("-")
        if ixt[1] == "equinixix" and "RS" not in r.description:
            ix = ixt[1]
            prefix_limit = int(math.ceil(int(r.prefix_received) * 1.25 / 10) * 10)
            print (
                "Peer: %s / %s, AS: %s, Pfx Received: %s / %s, IX : %s "
                % (neighbor, r.description, r.peer_as, r.prefix_received, prefix_limit, ix)
            )
Esempio n. 41
0
#!/usr/bin/python
# RMZ 2014

import sys, math
from jnpr.junos.utils.config import Config
from jnpr.junos import Device
from jnpr.junos.factory import loadyaml
globals().update(loadyaml('bgp-peer.yml'))


dev = Device(host='cr-xx-01', user='******', password='******' )
try:
  dev.open()
  results = BgpPeerTable(dev).get()
  cu = Config(dev)
except Exception as err:
  print err
  sys.exit(1)

for r in results:
  if r.peer_type == "External" and r.table == "inet.0" and r.policy != 'none' :
    neighbor,port = r.peer_address.split('+')
    ixt = r.policy.split('-')
    if ixt[1] == 'equinixix' and "RS" not in r.description :
      ix = ixt[1]
      prefix_limit = int(math.ceil(int(r.prefix_received)*1.25/10)*10)
      print("Peer: %s / %s, AS: %s, Pfx Received: %s / %s, IX : %s " % (neighbor, r.description, r.peer_as, r.prefix_received, prefix_limit, ix))
      cu.load("set protocols bgp group ipv4-%s-peer neighbor %s family inet unicast prefix-limit maximum %s" % (ix, neighbor, prefix_limit), format="set") 

cu.pdiff()
cu.commit()
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.factory import loadyaml

globals().update( loadyaml('flowsession.yml'))

dev = Device('10.10.1.1')
cu = Config(dev)

dev.open()
session_table = SessionTable(dev)
session_table.get()

for s in session_table:
  if session_table.keys():
    if s.session_direction == 'In' and s.destination_address == '192.168.0.105' and s.destination_port == '22' and s.session_protocol == 'tcp':
      block_src = {'Address': s.source_address}
      rsp = cu.load( template_path="add-global-address-book-template.conf", template_vars=block_src )
      clearflow = dev.rpc.clear_flow_session(destination_prefix=s.destination_address, source_prefix=s.source_address, destination_port=s.destination_port, protocol=s.session_protocol)
      cu.commit()

dev.close()
Esempio n. 43
0
### ---------------------------------------------------------------------------
### MAIN
### ---------------------------------------------------------------------------

args = parseargs()  

def die(msg):
  sys.stderr.write("ERROR: {}\n".format(msg))
  sys.exit(1)

if args.upf is None: die("You must specify -U")
if args.dnf is None: die("You must specify -D")
if args.upi is None: die("You must specify -i")
if args.dni is None: die("You must specify -d")

PimJoinTable = loadyaml("defs-pim.yml")['PimJoinTable']

up = PimJoinTable(path=args.upf).get()
dn = PimJoinTable(path=args.dnf).get()

if not '.' in args.dni: args.dni += '.0'
if not '.' in args.upi: args.upi += '.0'

# upstream is easy since there is only 1 up_iface per (S,G)
up_keys = set([i.name for i in up if i.up_iface == args.upi])

# downstream is tricky since there can be many per (S,G)
dn_keys = set([i.name for i in dn if args.dni in i.dn_iface])

missing = up_keys - dn_keys
print "MISSING {} (S,G) entries".format(len(missing))
Esempio n. 44
0
"""
Pythonifier for ARP Table/View
"""
from jnpr.junos.factory import loadyaml
from os.path import splitext
_YAML_ = splitext(__file__)[0] + '.yml'
globals().update(loadyaml(_YAML_))
Esempio n. 45
0
from jnpr.junos.factory import loadyaml
from jnpr.junos import Device

globals().update(loadyaml("/root/pyez/interfaces_table.yml"))
dev = Device(host="172.2.3.5", user="******", ssh_private_key_file="/root/.ssh/VRF")
dev.open()
tbl = IfacesEthernetTable(dev)
tbl.get()
for k in tbl:
    print k.items()
    for l in k.items()[2][1]:
        print l.items()