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()
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 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(): ''' 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 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
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) cfg.load("set system login user pyez class operator", format='set') cfg.load("set system login user pyez full-name pyez-test-" + str(int(10000 * random.random())),
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
eth = EthPortTable(a_device) eth.get() pprint(eth.items()) #### Getter operations print "\nRoute Table Get" print '-' * 50 z_routes = RouteTable(a_device) z_routes.get() pprint(z_routes.items()) #### Config operations print print "Current static routes" print '-' * 50 pprint(z_routes.keys()) print # Create config object cfg = Config(a_device) cfg.lock() config_str = """ routing-options { static { route 1.1.1.0/24 next-hop 10.220.88.1; route 1.1.2.0/24 next-hop 10.220.88.1; route 1.1.3.0/24 next-hop 10.220.88.1; } } """
#This program aims at getting the list of routes available on the device from jnpr.junos import Device as d from jnpr.junos.op.routes import RouteTable #Module to import Route-table #Make the connection to the device and open the device dev = d(host='192.168.0.92',user='******',password='******') dev.open() #Get the RouteTable and assign to a variable routes = RouteTable(dev).get() # Get method will help you pull the routes #Basically, you got the dictionary, the simplest way to get the routes is routes.keys() #To get the routes in the linear fashion for i in routes.keys(): print i
if len(fbc) > 0: print "\tbad community(s): " + str(fbc) #CREATE ROUTES IN ADDR/MASK FORMAT fullroute = y + "/" + bt[y]['rt_prefix_length'] if fullroute in hosts[x]['badroutes']: if flag == 0: print "Route " + y + "/" + bt[y][ 'rt_prefix_length'] + " contains:" print "\tis a bad route." flag = 1 #CHECK ADVERTISED ROUTES for y in hosts[x]['checkann'].keys(): routes = RouteTable(dev) routes.get(advertising_protocol_name="bgp", neighbor=y) adv = routes.keys() nf = [] print "Checking advertised routes to neighbor " + y + " " + str( hosts[x]['checkann'][y]) for z in hosts[x]['checkann'][y]: if z not in adv: print "\t" + z + " not found" nf.append(z) if len(nf) == 0: print "\tAll OK!" dev.close()
def main(): hosts = ['XX.YY.ZZ.EE'] user = '******' for host in hosts: # https://www.juniper.net/techpubs/en_US/junos-pyez1.0/topics/topic-map/junos-pyez-authenticating-users-with-ssh-keys.html dev = Device(host=host, user='******', ssh_private_key_file='/home/bot/.ssh/id_rsa.pub' ) # password=password) # Open the connection & config try: print "Opening connnection to:", host dev.open() except Exception as err: print "Cannot connect to device:", err return dev.timeout = 300 yaml_plkanet = ''' --- prefixlist: name: pl-kanet prefixes:''' # Getting information through Table/View tblrt = RouteTable(dev) tblrt.get(table='RI-PPPoE-INET.inet.0', community_name='community-city') ip_list = [] for route_item in tblrt.keys(): ip_list.append(IPNetwork(route_item)) # summarize groups of IP subnets and addresses, # merging them together where possible to create the smallest possible list of CIDR subnets ip_list = cidr_merge(ip_list) for route_item in ip_list: yaml_plkanet += "\n - " + str(route_item) pl_config = yaml.load(yaml_plkanet) dev.bind(cu=Config) # Lock the configuration, load changes, commit print "Locking the configuration on:", host try: dev.cu.lock() except LockError: print "Error: Unable to lock configuration on:", host dev.close() return print "Loading configuration changes on:", host try: dev.cu.load('''delete policy-options prefix-list pl-kanet''', format='set') dev.cu.load(template=pl_template, template_vars=pl_config, format='text') except ValueError as err: print err.message except Exception as err: if err.rsp.find('.//ok') is None: rpc_msg = err.rsp.findtext('.//error-message') print "Unable to load config changes: ", rpc_msg print "Unlocking the configuration on:", host try: dev.cu.unlock() except UnlockError: print "Error: Unable to unlock configuration on:", host dev.close() return if dev.cu.diff() is None: print "configuration is up-to-date" else: print "configuration differences:", dev.cu.pdiff() print "Committing the configuration on:", host try: dev.cu.commit() except CommitError: print "Error: Unable to commit configuration on:", host print "Unlocking the configuration on:", host try: dev.cu.unlock() except UnlockError: print "Error: Unable to unlock configuration on:", host dev.close() return print "Unlocking the configuration on:", host try: dev.cu.unlock() except UnlockError: print "Error: Unable to unlock configuration on:", host print "Closing connection to:", host dev.close()