def main(): ''' Connect to Juniper device using PyEZ. Display the routing table. ''' pwd = getpass('88newclass: ') ip_addr = raw_input("184.105.247.76\nEnter Juniper SRX IP: ") ip_addr = ip_addr.strip() juniper_srx = { "host": ip_addr, "user": '******', "password": pwd } print "\n\nConnecting to Juniper SRX...\n" # create device object with all the arguments in the dictionary a_device = Device(**juniper_srx) a_device.open() # get routing table routes = RouteTable(a_device) routes.get() print "\nJuniper SRX Routing Table: " for a_route, route_attr in routes.items(): print "\n" + a_route for attr_desc, attr_value in route_attr: print " {} {}".format(attr_desc, attr_value) print
def getroutes(thedevice): """ Retrieve routing table """ routes = RouteTable(thedevice) routes.get() return routes
def get_routing_table(self, **kvargs): """ Function that gathers the routing table from a device. It returns the whole routing table if no route is specified. If route is specified, next_hop can be also specified and routing table nexthop output will be compared against it. """ try: tbl = RouteTable(self._conn) except ConnectError as c_error: raise FatalError(c_error) complete_rt = tbl.get() if 'route' in kvargs.keys(): route = kvargs['route'] print ('route', route) if route != 'None': single_rt = tbl.get(route) # Routing Table dictionary rt = {} for item in tbl: # Remove "RouteTableView:" from item = RouteTableView:0.0.0.0/0 destination = str(item).split(":")[1] rt[destination] = [item.nexthop, item.age, item.via, item.protocol] return rt
def display_static_routes(device): route = RouteTable(device) route.get() print "Current routes:" for line in route.get(): pprint(line)
def do_something(params): device_connection = Device(**params) device_connection.open() # device_connection.facts_refresh() facts = device_connection.facts # response_xml_element = device_connection.rpc.get_software_information(normalize=True) # print(etree.tostring(response_xml_element)) # pprint(facts) print("{0} {1} {0}".format('=' * 37, facts['hostname'])) routing_table = RouteTable(device_connection) routing_table.get() print("RIB:") for prefix in routing_table: print(f"Destination : {prefix.key}\n" f"Via: {prefix.via}\n" f"Nexthop: {prefix.nexthop}\n" f"Protocol: {prefix.protocol}\n\n") print("{}".format('=' * 80)) arp_table = ArpTable(device_connection) arp_table.get() print("ARP table:") for entry in arp_table: print(f"IP : {entry.ip_address}\n" f"MAC: {entry.mac_address}\n" f"Interface: {entry.interface_name}\n\n") device_connection.close()
def main(): ''' Connect to Juniper device using PyEZ. Display the routing table. ''' pwd = getpass() try: ip_addr = raw_input("Enter Juniper SRX IP: ") except NameError: ip_addr = input("Enter Juniper SRX IP: ") ip_addr = ip_addr.strip() juniper_srx = {"host": ip_addr, "user": "******", "password": pwd} print("\n\nConnecting to Juniper SRX...\n") a_device = Device(**juniper_srx) a_device.open() routes = RouteTable(a_device) routes.get() print("\nJuniper SRX Routing Table: ") for a_route, route_attr in routes.items(): print("\n" + a_route) for attr_desc, attr_value in route_attr: print(" {} {}".format(attr_desc, attr_value)) print("\n")
def main(): pwd = getpass() juniper = { "host": "50.76.53.27", "user": "******", "password": pwd } a_device = Device(**juniper) a_device.open() table = RouteTable(a_device) table.get() print print "Juniper SRX Routing Table" print for route, rtable in table.items(): rtable = dict(rtable) #print stats nexthop = rtable['nexthop'] age = rtable['age'] via = rtable['via'] protocol = rtable['protocol'] print route print " NextHop %s" % (nexthop) print " age %s" % (age) print " via %s" % (via) print " protocol %s" % (protocol) print
def main(): ''' Connect to Juniper device using PyEZ. Display the routing table. ''' pwd = getpass() ip_addr = raw_input("Enter Juniper SRX IP: ") ip_addr = ip_addr.strip() juniper_srx = { "host": ip_addr, "user": "******", "password": pwd } print "\n\nConnecting to Juniper SRX...\n" a_device = Device(**juniper_srx) a_device.open() routes = RouteTable(a_device) routes.get() print "\nJuniper SRX Routing Table: " for a_route, route_attr in routes.items(): print "\n" + a_route for attr_desc, attr_value in route_attr: print " {} {}".format(attr_desc, attr_value) print "\n"
def gather_routes(): '''Return the routing table from the device''' # Pass in NETCONF connection to RouteTable object routing_table = RouteTable(device_conn) # Retrieve routing table entries in dictionary like format routing_table.get() return routing_table
def runTest(self): route_table = RouteTable(self.dev) routes = route_table.get('123.123.123.1/24') # Checks for a single route recieved via BGP. Uncomment to enable self.assertEqual(len(routes), 1)
def gather_routes(): '''Return the routing table from the device''' # Pass in NETCONF connection to RouteTable object routing_table = RouteTable(device_conn) # Retrieve routing table entries in dictionary like format routing_table.get() # Return keys and values of data structure return routing_table.items()
class JuniperObject(object): def __init__(self, jnp_dev): self.conn = jnp_dev self.config = None self.ports = {} self.routes = {} def __get_ports(self): self.ports = EthPortTable(self.conn) self.ports.get() def __get_routes(self): self.routes = RouteTable(self.conn) self.routes.get() def config_mode(self): self.config = Config(self.conn) self.config.lock() def send_command(self, command, cmd_format, cmd_merge): self.config.load(command, format=cmd_format, merge=cmd_merge) def file_command(self, file_path, file_format, file_merge): self.config.load(path=file_path, format=file_format, merge=file_merge) def get_diff(self): return self.config.diff() def commit(self, comment=None): self.config.commit(comment=comment) def rollback(self): self.config.rollback(0) def unlock(self): self.config.unlock() def show_all_interfaces(self): self.__get_ports() print "Juniper SRX Interface Statistics" for my_key in self.ports.keys(): print "---------------------------------" print my_key + ":" print "Operational Status: " + self.ports[my_key]['oper'] print "Packets In: " + self.ports[my_key]['rx_packets'] print "Packets Out: " + self.ports[my_key]['tx_packets'] def show_all_routes(self): self.__get_routes() print "Juniper SRX Routing Table" for my_key in self.routes.keys(): print "---------------------------------" print my_key + ":" print " Next Hop: {}".format(self.routes[my_key]['nexthop']) print " Age: {}".format(self.routes[my_key]['age']) print " via: {}".format(self.routes[my_key]['via']) print " Protocol: {}".format(self.routes[my_key]['protocol'])
def display_static_routes(a_device): """Display static routes.""" routes = RouteTable(a_device) routes.get() print "\nCurrent static routes" print '-' * 50 pprint(routes.keys()) print
def get_junos_route_table(device): details = settings.devices[device.name] dev = JunosDevice(details['mgmt_ip'], user=details['username'], passwd=details['password'], port=details['mgmt_port']) dev.open() routes = RouteTable(dev) routes.get() dev.close() route_list = dict([item for item in routes.items() if item[1][0][1] not in ['Local','Access-internal']]) return(route_list)
def main(args): '''Acquire necessary input options, interact with SRX device as specified per CLI args.''' parser = argparse.ArgumentParser( description='Interact with specified SRX device as specified') parser.add_argument('--version', action='version', version=__version__) parser.add_argument('-d', '--datafile', help='specify YAML file to read router info from', default=SRX_FILE) parser.add_argument( '--prompt', action='store_true', help='prompt for router info (do not try to read in from file)', default=False) parser.add_argument('-v', '--verbose', action='store_true', help='display verbose output', default=False) args = parser.parse_args() # Debugging #if args.verbose: # print 'Args = {}'.format(args) # Initialize data structures mysrx = {} if not args.prompt: mysrx = yaml_input(args.datafile, args.verbose) # Debugging #if args.verbose: # print 'mysrx = {}'.format(mysrx) else: if args.verbose: print 'Prompting specified - asking user for all connection details' check_input(mysrx, args.verbose) mysrx_conn = Device(host=mysrx['HOST'], user=mysrx['USER'], password=mysrx['PASSWORD']) if args.verbose: print 'Opening NETCONF connection to {}...'.format(mysrx['HOST']) mysrx_conn.open() # Set timeout - default of 30 seconds can be problematic, must set after open() mysrx_conn.timeout = TIMEOUT routes = RouteTable(mysrx_conn) if args.verbose: print 'Gathering RouteTable info from {}...'.format(mysrx['HOST']) routes.get() print 'Routing Table for {}:'.format(mysrx['HOST']) for rt_key in routes.keys(): print '{}:'.format(rt_key) for rt_subkey in routes[rt_key].keys(): print ' \\{:>10}: {:<20}'.format(rt_subkey, routes[rt_key][rt_subkey]) mysrx_conn.close()
def gather_routes(): DEV = check_connected() ROUTE_TABLE = RouteTable(DEV) ROUTE_TABLE.get() #print("\n") #print("Printing ROUTE TABLE") #print("-"*30) #pprint(ROUTE_TABLE.items()) return ROUTE_TABLE.items()
def main(): pwd = getpass() srx = { "hostname": "srx1.twb-tech.com", "host": "184.105.247.76", "user": "******", "password": pwd } srx_device = Device(**srx) srx_device.open() print("\nThe current timeout is {} seconds.".format(srx_device.timeout)) srx_device.timeout = 120 print("\nThe updated timeout is {} seconds.".format(srx_device.timeout)) routes = RouteTable(srx_device) routes.get() routes_dict = {} for item in routes.items(): route = item[0] nexthop = item[1][3][1] age = item[1][2][1] via = item[1][1][1] protocol = item[1][0][1] print("\n") print("{}\n".format(route)) print("nexthop: {}\n".format(nexthop)) print("age: {}\n".format(age)) print("via: {}\n".format(via)) print("protocol: {}\n".format(protocol)) print("\n") routes_dict.update({ route: { "nexthop": nexthop, "age": age, "via": via, "protocol": protocol } }) print("\n") pprint(routes_dict) print("\nJust the intfs ma'am") print("*******************") pprint(routes) print("*******************\n")
def checkBGP(): with open(logfile, 'ab') as a: a.write("Running BGP Check Script at: %s \n" % timestamp ) try: # Open SRX session dev.open() with open(logfile, 'ab') as a: a.write("Opened connection to %s \n" % deviceIP) except: with open(logfile, 'ab') as a: a.write("ERR: FAILED TO OPEN CONNECTION TO %s \n" % deviceIP) sys.exit(0) # Pull device routing table, then keep only BGP originated routes allroutes = RouteTable(dev) bgp = allroutes.get(protocol="bgp").keys() # Close SRX session dev.close() # Check for local temp file - if it doesn't exist, then assume first-run # and create file with data. if not os.path.isfile(tempfile): with open(tempfile, 'w+b') as a: a.write(str(bgp)) sys.exit(0) # Local file used to keep track of BGP learned routes with open(tempfile, 'ab') as a: lastroutes = a.readlines() # Compare if routes are different if str(bgp) == str(lastroutes[0]): sys.exit(0) if str(bgp) != str(lastroutes[0]): pass # Delete file, then re-create with new route list #os.remove(tempfile) with open(tempfile, 'w+b') as a: a.write(str(bgp)) # Create Status list, by checking received routes in bgp object status = [] for name,prefix in prefixDict.items(): if prefix in bgp: status.append("%s - RECEIVED" % name) if not prefix in bgp: status.append("%s - MISSING" % name) # Send alert message sendMail(str(lastroutes[0]), str(bgp), status)
def main(): """ FUNCTION TO PERFORM INIT """ parser = argparse.ArgumentParser(add_help=True) parser.add_argument("-n", action="store", help="Specify stack name") parser.add_argument("-v", action="store", help="Specify VRF") parser.add_argument("-f", action="store", help="Specify YAML/HOT file") parser.add_argument("-e", action="store", help="Specify ENV file") args = parser.parse_args() if args.n: stack_name = args.n if args.v: routing_instance_name = args.v if args.f: hot_file = args.f if args.e: env_file = args.e dev = Device(host='10.84.18.253', user='******', password='******').open() vrftbl = VRF(dev).get(values=True) iftbl = InterfaceTable(dev).get() routetbl = RouteTable(dev).get(protocol="static") interface, route_target = routingInstance(vrftbl, routing_instance_name) peer_logical = peerUnit(iftbl, interface) prefix = getPrefix(routetbl, peer_logical) pushParams(prefix, route_target, hot_file, env_file, stack_name) dev.close()
def main(args): '''Acquire necessary input options, interact with SRX device as specified per CLI args.''' parser = argparse.ArgumentParser( description='Interact with specified SRX device as specified') parser.add_argument('--version', action='version', version=__version__) parser.add_argument('-d', '--datafile', help='specify YAML file to read router info from', default=SRX_FILE) parser.add_argument('--prompt', action='store_true', help='prompt for router info (do not try to read in from file)', default=False) parser.add_argument('-v', '--verbose', action='store_true', help='display verbose output', default=False) args = parser.parse_args() # Debugging #if args.verbose: # print 'Args = {}'.format(args) # Initialize data structures mysrx = {} if not args.prompt: mysrx = yaml_input(args.datafile, args.verbose) # Debugging #if args.verbose: # print 'mysrx = {}'.format(mysrx) else: if args.verbose: print 'Prompting specified - asking user for all connection details' check_input(mysrx, args.verbose) mysrx_conn = Device(host=mysrx['HOST'], user=mysrx['USER'], password=mysrx['PASSWORD']) if args.verbose: print 'Opening NETCONF connection to {}...'.format(mysrx['HOST']) mysrx_conn.open() # Set timeout - default of 30 seconds can be problematic, must set after open() mysrx_conn.timeout = TIMEOUT routes = RouteTable(mysrx_conn) if args.verbose: print 'Gathering RouteTable info from {}...'.format(mysrx['HOST']) routes.get() print 'Routing Table for {}:'.format(mysrx['HOST']) for rt_key in routes.keys(): print '{}:'.format(rt_key) for rt_subkey in routes[rt_key].keys(): print ' \\{:>10}: {:<20}'.format(rt_subkey, routes[rt_key][rt_subkey]) mysrx_conn.close()
def main(): pwd = getpass() a_device = Device(host='184.105.247.76', user=USER, password=pwd) a_device.open() routes = RouteTable(a_device) routes.get() print for k, v in routes.items(): print k for info, stat in v: print("{} {}".format(info, stat)) print print
def main(): ''' Main function ''' a_device = remote_conn(HOST, USER, PWD) if not a_device: sys.exit('Fix the above errors. Exiting...') route_table = RouteTable(a_device) route_table.get() for route in route_table.keys(): print route route_items = dict(route_table[route].items()) print ' Oper: %s' % (route_items['nexthop']) print ' rx: %s' % (route_items['age']) print ' tx: %s' % (route_items['via']) print ' prot: %s' % (route_items['protocol']) print
def main(): ''' Formatting the routing table ''' pwd = getpass() try: a_device = Device(host='184.105.247.76', user='******', password=pwd) a_device.open() route_table = RouteTable(a_device) route_table.get() print "\n"*2 print "Juniper SRX Routing Table: \n" for route, route_att in route_table.items(): print route for desc, value in route_att: print ("\t {0} {1}").format(desc, value) print "\n" print except: print print "Authentication Error" print
def main(): juniper_srx = { "host": "184.105.247.76", "user": "******", "password": "******" } print("\n\nConnecting to Juniper SRX...\n") a_device = Device(**juniper_srx) a_device.open() routes = RouteTable(a_device) routes.get() print("\nJuniper SRX Routing Table: ") for a_route, route_attr in routes.items(): print("\n" + a_route) for attr_desc, attr_value in route_attr: print(" {} {}".format(attr_desc, attr_value)) print("\n")
def main(): ''' Formatting the routing table ''' pwd = getpass() try: a_device = Device(host='184.105.247.76', user='******', password=pwd) a_device.open() route_table = RouteTable(a_device) route_table.get() print "\n"*2 print "Juniper SRX Routing Table: \n" for route in route_table.keys(): print route print " {0}".format(route_table[route]['nexthop']) print " {0}".format(route_table[route]['age']) print " {0}".format(route_table[route]['via']) print " {0}".format(route_table[route]['protocol']) print "\n" print except: print print "Authentication Error" print
def main(): """ FUNCTION TO PERFORM INIT """ try: dev = Device(host='', user='', password='').open() vrftbl = VRF(dev).get(values=True) iftbl = InterfaceTable(dev).get() routetbl = RouteTable(dev).get(protocol="static") routing_instance_name = str(sys.argv[1]) interface, route_target = routingInstance(vrftbl, routing_instance_name) peer_logical = peerUnit(iftbl, interface) prefix = getPrefix(routetbl, peer_logical) print route_target, prefix except: print "No Info found/Cannot connect"
from jnpr.junos import Device from jnpr.junos.op.routes import RouteTable dev = Device(host='xxxx', user='******', password='******', gather_facts=False) dev.open() tbl = RouteTable(dev) tbl.get() #tbl.get('10.13.10.0/23', protocol='static') print tbl for item in tbl: print 'protocol:', item.protocol print 'age:', item.age print 'via:', item.via print dev.close()
def test_table_json(self): tbl = RouteTable(self.dev) tbl.get('10.48.21.71') self.assertEqual( json.loads(tbl.to_json())["10.48.21.71/32"]["protocol"], "Local")
def test_table_union(self): tbl = RouteTable(self.dev) tbl.get() self.assertEqual(tbl[0].via, 'em0.0')
def gather_routes(device): routes = RouteTable(device) routes.get() return routes
from jnpr.junos import Device from jnpr.junos.op.routes import RouteTable a_device = Device(host="184.105.247.76", user='******', password='******') a_device.open() a_device.timeout = 120 routes = RouteTable(a_device) routes.get() for route, param in routes.items(): print route for k, v in param: print k, v print ''
def __get_routes(self): self.routes = RouteTable(self.conn) self.routes.get()
from sys import exit from lxml import etree from jnpr.junos.utils.config import Config Host = raw_input('Enter Hostname or IP address of Device: ') dev = Device(host=Host, user='******', password='******').open() Peer = raw_input('Enter Peering Device: ') class style: BOLD = '\033[1m' END = '\033[0m' route_table = RouteTable(dev) route_table.get(protocol='bgp') for key in route_table: if key.nexthop == Peer: print key.name + 'Nexthop: ' + key.nexthop + 'Via: ' + key.via + ' Protocol: ' + key.protocol Continue = raw_input('Do you wish to pull route(s), Yes or No: ') if Continue == 'Yes': proute = raw_input('Enter route to pull in format X.X.X.X/X: ') prefix = raw_input('Enter Vendor Prefix: ') ticket = raw_input('Enter Ticket Number: ') else: dev.close()
via vlan.0 protocol Local """ from jnpr.junos import Device from jnpr.junos.op.routes import RouteTable from getpass import getpass pwd = getpass() a_device = Device(host="50.76.53.27", user='******', password=pwd) # Establish connection with device a_device.open() # Instantiate an RouteTable object ports = RouteTable(a_device) # Retrieve data from instantiated object ports.get() for a_route in ports.keys(): print ("%s\n\t%s\n\t%s\n\t%s\n\t%s\n") % \ (a_route, ports[a_route]['nexthop'], ports[a_route]['age'], ports[a_route]['via'], ports[a_route]['protocol'] ) # mm = tamtamnewclass
#!/usr/bin/env python from pprint import pprint from jnpr.junos import Device from jnpr.junos.op.routes import RouteTable dev = Device(host='46.226.4.24', user='******', password='******') dev.open() tbl = RouteTable(dev) tbl.get('0.0.0.0/0', protocol='aggregate') print tbl for item in tbl: print 'protocol:', item.protocol print 'age:', item.age print 'via:', item.via print dev.close()
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()
from jnpr.junos.factory.factory_loader import FactoryLoader import yaml # from existing table/view from jnpr.junos.op.routes import RouteTable tbls = RouteTable(path='/var/tmp/get-route-information.xml') tbls.get() for item in tbls: print 'protocol:', item.protocol print 'age:', item.age print 'via:', item.via # From user defined table/view yaml_data=""" --- RemoteVxlanTable: rpc: get-ethernet-switching-vxlan-rvtep-info item: vxlan-source-vtep-information/vxlan-remote-vtep-information key: remote-vtep-address view: RemoteVxlanView RemoteVxlanView: groups: vnis: vxlan-dynamic-information fields_vnis: vni: vxlan-format/vn-id """
print("Using XML RPC to get info, then parse XML reply:") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") lxml = dev.rpc.get_arp_table_information() arp_table = lxml.findall('arp-table-entry') for entry in arp_table: print("MAC: %s, IP: %s" % (entry.findtext('mac-address').strip(), entry.findtext('ip-address').strip())) # -------------------------------------------------------------- print("Using tables and views to get route info:") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") from jnpr.junos.op.routes import RouteTable routes = RouteTable(dev) routes.get() for route in routes.keys(): if routes[route]['protocol'] == 'Local': print(route) # -------------------------------------------------------------- print("Configure with set commands:") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~") from jnpr.junos.utils.config import Config import random cfg = Config(dev)
# some pyez script to get some routes using Tables and Views # you can create your own tables and views # first import some modules from jnpr.junos import Device from jnpr.junos.op.routes import RouteTable from pprint import pprint as pp # define device object and use open method to connect # netconf used to connect to device dev = Device(host='vsrx04.t-i.demo',user='******',password='******') dev.open() # now bind this table to dev and get all routes from this device # we could be looking for specific route but we're just loading complete route table for now. routes = RouteTable(dev) routes.get() # every route is a View.RouteTableView object from this routes OpTable.RouteTable class. # now loop through this list and print View.RouteTableView object elements for route in routes: pp (route.items()) pp (route.via) # close netconf connection dev.close()
def gather_routes(device): # Create RouteTable view object routes = RouteTable(device) # Get all routes routes.get() return routes
#!/usr/bin/env python from pprint import pprint from jnpr.junos import Device from jnpr.junos.op.routes import RouteTable dev = Device(host='46.226.4.24', user='******', password='******' ) dev.open() tbl = RouteTable(dev) tbl.get('0.0.0.0/0', protocol='aggregate') print tbl for item in tbl: print 'protocol:', item.protocol print 'age:', item.age print 'via:', item.via print dev.close()
from jnpr.junos import Device from jnpr.junos.op.routes import RouteTable dev = Device(host='34.208.13.114', user='******', password='******', gather_facts=False) dev.open() tbl = RouteTable(dev) tbl.get() print(tbl) for item in tbl: print('protocol:', item.protocol) print('age:', item.age) print('via:', item.via) print() dev.close()
def gather_routes(): routing_table = RouteTable(connection) routing_table.get() return dict(routing_table.items())
#!/bin/env python #pynet-sf-srx ansible_ssh_host=184.105.247.76 juniper_user=pyclass juniper_passwd=88newclass import sys from jnpr.junos import Device from jnpr.junos.op.routes import RouteTable a_device = Device(host='184.105.247.76', user='******', password='******') a_device.open() route_table = RouteTable(a_device) rt = route_table.get() routes = rt.items() print "\n" for key,values in routes: print key for k,v in values: print " %s %s" %(k,v)