def _arista_get_facts_api(task, options={}): c = pyeapi.connect( transport=task.host.get('secure_api', 'https'), host=task.host.hostname, username=task.host.username, password=task.host.password, port=task.host.port ) output = c.execute([ ARISTA_GET_FACTS, ARISTA_GET_INT, ARISTA_GET_DOMAIN ]) if verbose_mode( user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET), needed_value=LEVEL2 ): printline() print(output) task.host[FACTS_DATA_HOST_KEY] = _arista_facts_api_converter( hostname=task.host.name, cmd_output=output, options=options )
def main(): """ Check if BGP/OSPF neighbors for an Arista device are ESTABLISHED/FULL. Anything else is CRITICAL """ # print("STARTING TIME " + str(datetime.datetime.now()) + "\n") args = parse_args() my_password = getpass("Password for user allowed to connect to eAPI: ") check_arista = Arista() connection = pyeapi.connect( transport="https", host=args.ip, username=args.username, password=my_password, port=args.port, ) node = Node(connection) if args.protocol == "bgp": check_arista.bgp_status(node, args.hostname) elif args.protocol == "ospf": check_arista.ospf_status(node, args.hostname, 0) else: print("CRITICAL - Command not supported or wrong")
def __init__(self, hostname, **kwargs): self.vrf = self.VRF_MGMT self.hostname = hostname self.proto = kwargs.get('proto') or self.DEFAULT_PROTOCOL self.port = kwargs.get('port') # explicit check for None, since setting port to 0 is # valid for on-box EOS. if self.port is None: self.port = socket.getservbyname(self.proto) self.user = kwargs.get('user') self.passwd = kwargs.get('passwd') if self.proto == 'socket': self.eapi = pyeapi.client.make_connection( 'socket', username=self.user, password=self.passwd, **kwargs.get('socket_opts')) else: self.eapi = pyeapi.connect(transport=self.proto, host=self.hostname, username=self.user, password=self.passwd)
def wrapper(self, protocol): api = pyeapi.connect(transport="http", host=protocol.host, port=protocol.conf["http"], username=protocol.username, password=protocol.password, return_node=True) test(self, protocol, api)
def _connect(self): self.node = pyeapi.connect(host=self.switch_descriptor.hostname, username=self.switch_descriptor.username, password=self.switch_descriptor.password, port=self.switch_descriptor.port, transport=self.transport, return_node=True, timeout=default_command_timeout)
def show_ports(switch): node = pyeapi.connect(transport="https", host=switch, username="******", password="******", port=None) interface_status = node.execute(["show interfaces status "]) return interface_status
def setUp(self): conf = TEST_SWITCHES[self.switch_name] self.node = pyeapi.connect(transport="http", host="127.0.0.1", port=conf["http"], username="******", password="******", return_node=True) self.connection = self.node.connection
def main(): switches = ["yo410.sjc.aristanetworks.com", "yo653.sjc.aristanetworks.com"] value = [] value1 = [] switch_neighbor = {} #value_dict = {"Local Port" : "" , "Neighbor Device" : "", "Neighbor Port" : ""} for switch in switches: value = [] #switch = switch[0] node = pyeapi.connect(protocol="https", host=switch, username="******", password="******", port=None) neighbor = node.execute(["show lldp neighbors"]) hostname = node.execute(["show hostname"]) #print hostname for i in range(0, len(neighbor['result'][0]['lldpNeighbors'])): value_temp = [] value_dict = {} value_dict["Local Port"] = str( neighbor['result'][0]['lldpNeighbors'][i]['port']) value_dict["Neighbor Device"] = str( neighbor['result'][0]['lldpNeighbors'][i]['neighborDevice']) value_dict["Neighbor Port"] = str( neighbor['result'][0]['lldpNeighbors'][i]['neighborPort']) if not value: value = [value, value_dict] #print value elif not value[0]: value = [value[1], value_dict] #print value else: value.append(value_dict) #print value switch_neighbor[switch] = value #print switch_neighbor[switch] my_topo = create_topo(switch, switch_neighbor[switch]) #print len(my_topo) #print my_topo #for key in switch_neighbor : # print ("******************************************************") # print ("LLDP Neighbors for %s") % key # print ("******************************************************") # for neighbors in switch_neighbor[key]: # print neighbors["Neighbor Device"] #print len(my_topo) #print my_topo dot = make_topology("My New Network", my_topo, switches) dot.view() dot.render(filename='Desktop/TopoDiag/NetworkDiag')
def executeCommand(ip, cmds, un='cvpuser', pwd='root'): ip = ip.strip() un = un.strip() pwd = pwd.strip() connection = pyeapi.connect(host=ip, username=un, password=pwd, timeout=10) resp = connection.execute(cmds) resp = json.dumps(resp, indent=4) return resp
def __post_init__(self, **_ignore): super().__post_init__(**_ignore) self.metadata.implementation = "EOS-PYEAPI" _conn = pyeapi.connect( host=self.host, transport=self.transport, username=self.username, password=self.password, ) self.connector = pyeapi.client.Node(_conn)
def eapi_conn(request): connection = pyeapi.connect( transport="https", host="0.0.0.0", username="******", password="******", port=9002, ) node = Node(connection) return node
def main(): args = get_args() ip = get_side(args.side) password = getpass("Enter your vEOS Password: ") node = pyeapi.connect(host=ip, password=password, return_node=True) add_route(node, args.host)
def main(): args = get_args() password = getpass("Enter your vEOS Password: ") node = pyeapi.connect(host=args.ip, password=password, return_node=True) config_diff(node) config_write(node, args.ip) scp(args.swi, '/mnt/flash/', args.ip, args.user, password) config_boot(node, args.swi) reload(node)
def get_connection(self): # set the default timeout logging.debug(f'Setting timeout to {self._timeout}') if not self._connection: logging.info(f'Connecting to switch {self._target}') self._connection = pyeapi.connect(transport=self._protocol, host=self._target, username=self._username, password=self._password, timeout=self._timeout) return self._connection
def switch_connect(usern, pw, switch): try: node = pyeapi.connect(host=switch, username=usern, password=pw, return_node=True) except pyeapi.eapilib.ConnectionError as err: print("WE ENCOUNTERED A CONNECTION ISSUE") print("Error command: %s" % err.command) print("Error message: %s" % err.message) return node
def connect_switch(self, command): # switch off certificate validation ssl._create_default_https_context = ssl._create_unverified_context switch_result = "" # set the default timeout logging.debug("setting timeout to %s", self._timeout) connection = pyeapi.connect(transport=self._protocol, port=self._port, host=self._target, username=self._username, password=self._password, timeout=self._timeout) logging.info("Connecting to switch %s", self._target) data = { "jsonrpc": "2.0", "method": "runCmds", "params": { "format": "json", "timestamps": "true", "autoComplete": "false", "expandAliases": "false", "cmds": [command], "version": 1 }, "id": "EapiExplorer-1" } try: logging.debug("Running command %s", command) switch_result = connection.send(json.dumps(data)) except (pyeapi.eapilib.ConnectionError, socket.timeout) as pyeapi_connect_except: logging.error("----------------------------------------------") logging.error("PYEAPI Client Connection Exception: %s", pyeapi_connect_except) logging.error("While connecting to switch %s", self._target) logging.error("----------------------------------------------") except pyeapi.eapilib.CommandError as pyeapi_command_except: logging.error("----------------------------------------------") logging.error("PYEAPI Client Command Exception: %s", pyeapi_command_except) logging.error("While connecting to switch %s", self._target) logging.error("----------------------------------------------") finally: return switch_result
def main(): ''' Ansible module to add/modify vlans on Arista switches ''' module = AnsibleModule( argument_spec=dict( host=dict(required=True), port=dict(default=443, required=False), username=dict(required=True), password=dict(required=True), transport=dict(default="https", required=False), vlan_name=dict(required=True), vlan_id=dict(required=True) #vlan_state=dict(default='present',required=False), ), supports_check_mode=True ) connection=pyeapi.connect(host=module.params['host'],username=module.params['username'],password=module.params['password'], port=module.params['port'],transport=module.params['transport']) switch=pyeapi.client.Node(connection) network_admin = AristaNetworkAdmin(switch) vlan=Vlan(module.params['vlan_id'],module.params['vlan_name']) with open("/tmp/eapi.log","w+") as f: if network_admin.vlan_exists(vlan): f.write("Exists: " + str(network_admin.vlan_exists(vlan)) + "\n") f.write("DEBUG: vlan %s with id %s exists \n" %(vlan.name,vlan.vlan_id)) module.exit_json(msg="vlan exists", changed=False) else: f.write("DEBUG: vlan %s with id %s does not exist or has a different name \n" %(vlan.name,vlan.vlan_id)) if module.check_mode: if network_admin.vlan_exists(vlan): f.write("Check Mode: Vlan already exists\n") module.exit_json(msg="Vlan already exits",changed=False) module.exit(msg="Check mode: Vlan would be added or updated with a new name",changed=True) f.write("Attempting add\n") status=network_admin.vlan_add(vlan) f.write("Add complete with result %s\n" %(str(status))) vl=network_admin.vlan_list(vlan) if status and vl: f.write("Vlan changed\n") module.exit_json(msg="Vlan successfully added/modified",changed=True) else: f.write("failed to add vlan\n") module.fail_json(msg="Vlan failed to add")
def main(hostname, username, password, afi, print_roas, print_matches, remote_vrp_file, vrp_url, extcomm, next_hop): """Compare EOS validation status to the expected results.""" passed = 0 failed = 0 local_results = collections.defaultdict(collections.Counter) extcomm_results = collections.defaultdict(collections.Counter) node = pyeapi.connect(host=hostname, username=username, password=password, return_node=True) local_as = get_local_as(node) vrp_tree = fetch_vrp(remote_vrp_file, vrp_url, node, afi) for network in BATCHES[afi]: cmd = f"show bgp {afi} unicast {network} longer-prefixes" if extcomm: cmd += " detail" data = node.enable([cmd])[0] for prefix, length, paths in iter_routes(data, local_as, extcomm, next_hop): for origin, status, ec_status in paths: match, expected, received, roas = compare_ov_state( vrp_tree, prefix, length, origin, status, ec_status) line = result_line(match, prefix, origin, status, expected, received) if match: passed += 1 if print_matches: click.echo(line) if print_roas: dump_roas(roas) else: failed += 1 click.echo(line) if print_roas: dump_roas(roas) local_results[status][expected] += 1 extcomm_results[status][received] += 1 click.echo("Comparison results:") click.secho(f" Passed: {passed}", fg="green") click.secho(f" Failed: {failed}", fg="red") print_results(local_results, "Expected") if extcomm: print_results(extcomm_results, "Received Ext-Community") return
def _arista_get_bgp_api(task, options={}): commands_to_execute = [ARISTA_API_GET_BGP] for vrf in task.host[VRF_NAME_DATA_KEY].keys(): if vrf not in VRF_DEFAULT_RT_LST: commands_to_execute.append(ARISTA_API_GET_BGP_VRF.format(vrf)) c = pyeapi.connect(transport=task.host.get('secure_api', 'https'), host=task.host.hostname, username=task.host.username, password=task.host.password, port=task.host.port) output = c.execute(commands_to_execute) if verbose_mode(user_value=os.environ.get("NETESTS_VERBOSE", NOT_SET), needed_value=LEVEL2): printline() print(output) task.host[BGP_SESSIONS_HOST_KEY] = _arista_bgp_api_converter( hostname=task.host.name, cmd_output=output, options=options)
def __init__(self, hostname, username=None, password=None, transport=None, port=None, ssh_config_file=None): self.hostname = hostname c_args = dict() c_args['username'] = os.getenv('EOS_USER') or os.getenv( 'USER') or username c_args['password'] = os.getenv('EOS_PASSWORD') or os.getenv( 'PASSWORD') or password if port: c_args['port'] = port ssh_config_file = ssh_config_file or os.getenv('EOS_SSH_CONFIG') if ssh_config_file: ssh_config = SSHConfig() ssh_config.parse(open(ssh_config_file)) found = ssh_config.lookup(hostname) if 'user' in found: c_args['username'] = found['user'] if 'hostname' in found: c_args['host'] = found['hostname'] if 'localforward' in found: port = int(first(found['localforward']).split()[0]) c_args['port'] = port c_args['host'] = 'localhost' else: c_args['host'] = hostname c_args['transport'] = transport or self.DEFAULT_TRANSPORT self.api = pyeapi.connect(**c_args)
def initiate_connection(self): # connection initiated as switch object parameter self.connected_switch = pyeapi.connect(transport='https', host=self.ip_addr, username=self.username, password=self.password, port=None) # As there is no usable way to parse connection errors on initiation state, # connection status is checked by executing simple "show hostname" command. # If successfull - label "connected" method is executed and label is displayed try: switch.switch_hostname = switch.connected_switch.execute( ['show hostname']) main_app.connected() main_app.display_label() # if not succsessfull - label "not_connected" method is executed and label is displayed except: main_app.not_connected() main_app.display_label()
def get_arista_route_table(device): details = settings.devices[device.name] conn = pyeapi.connect(host=details['mgmt_ip'], username=details['username'], password=details['password'], port=details['mgmt_port']) route_list = conn.execute(['show ip route'])['result'][0]['vrfs']['default']['routes'] return(route_list)
BGP_Problemiolanlar = [] vericekme_problemiolanlar = [] problemli_cihazlar = [] i = 101 while i < 201: fourh_octet = i IP = "10.129.34." + str(fourh_octet) i = i + 1 switches.append(IP) for i in switches: try: node = pyeapi.connect(transport="https", host=i, username="******", password="******", port=None) hostname = node.execute(["show hostname"]) cihazin_adi = hostname['result'][0]['hostname'] leafnumber = cihazin_adi.split("-") lldp = node.execute(["show lldp neighbors"]) cihazdaki_komsuluk = list(lldp['result'][0]['lldpNeighbors']) cihazdaki_komsuluk.reverse() cihazdaki_lldp_sayisi = len(cihazdaki_komsuluk) cvx = node.execute(["show management cvx"]) po100 = node.execute(["show interfaces port-Channel 100 status"])
def parse_args(argv): switches = [] switch_dict = {} nodes = [] switch_dict = {} hostname_list = [] parser = optparse.OptionParser() parser.add_option( '-b', help='This option enables KBps to be dispalyed. Default is off.', dest='mbps', default=False, action='store_true') parser.add_option( '--count_packet', help= 'This option enables packet count to be dispalyed. Default is off.', dest='pkts', default=False, action='store_true') parser.add_option( '--safe', help= 'This option enables configurations to be backed up before running the program and restored upon exiting (Thus keeping the load-interval commands as previous). Default is off.', dest='safe', default=False, action='store_true') parser.add_option('-u', help='Username. Mandatory option', dest='username', action='store') parser.add_option('-p', help='Password. Mandatory option', dest='password', action='store') parser.add_option( '-l', help= 'explicit interface load-interval rate. If set then every interesting interface has its load-interval set, and subsequently removed when packet-rate drops below 2pps. Values 5-300. By default the programs sets the system default load-interval to 5', dest='load_interval', type=int, default=False, action='store') parser.add_option( '-r', help= 'min packet rate. Any interface with a rate above this will report status. Default is 2 pps.', dest='ppsrate', type=int, default=2, action='store') parser.add_option( '-a', help= 'One or more hostnames (or IP addresses) of the switches to poll. Comma separated. Mandatory option with multiple arguments', dest='hostnames', action='store') parser.add_option( '-i', help= 'optional argument with multiple arguments. Ethernet Ports Only- Format: Ethernet<num>, or Eth<num>, comma separated, or range separated with' '-' ' e.g. Eth21-45 or Eth1,Eth7,Eth21-45', dest='interfaces', action='store') (opts, args) = parser.parse_args() mandatories = ['username', 'password', 'hostnames'] for m in mandatories: if not opts.__dict__[m]: print "mandatory option is missing\n" parser.print_help() print "\n\n" exit(-1) hostname_list = opts.hostnames.split(',') if opts.interfaces != None: interface_list_parsed = opts.interfaces.split(',') for interface in interface_list_parsed: if '-' in interface: interface_range_start_stop = interface.split('-') for line in interface_range_start_stop: if not_num_only_match(line): for x in line[::-1]: if x.isalpha(): y = line.split(x) interface_range_start_stop[0] = y[1] interface_range = range( int(interface_range_start_stop[0]), (int(interface_range_start_stop[1]) + 1), 1) for i in interface_range: interface_list_parsed.append("Ethernet" + str(i)) break elif 'Ethernet' in interface: pass else: for x in interface[::-1]: if x.isalpha(): y = interface.split(x) interface_list_parsed.append("Ethernet" + str(y[1])) break interface_list_remove = [] for interface in interface_list_parsed: if '-' in interface: interface_list_remove.append(interface) elif 'Ethernet' not in interface: interface_list_remove.append(interface) else: pass interface_list = [ x for x in interface_list_parsed if x not in interface_list_remove ] else: interface_list = [] for IPorHM in hostname_list: switch = connect(opts.username, opts.password, IPorHM) switches.append(switch) for IPorHM in hostname_list: node = pyeapi.connect(host=IPorHM, user=opts.username, password=opts.password, transport='http') nodes.append(node) switch_dict = {k: v for k, v in zip(hostname_list, switches)} return opts.safe, interface_list, nodes, switch_dict, hostname_list, opts.mbps, opts.load_interval, opts.ppsrate, opts.pkts
def get_arista_interfaces(device, username, password, DEBUG=False): """ connect to an arista switch and get all the interface information trim down the data, we don't need all the fields that are returned :param device: :param username: :param password: :return: dict """ removed_fields = ['forwardingModel', 'interfaceCounters', 'interfaceStatistics', 'loopbackMode', 'memberInterfaces', 'fallbackEnabled', 'fallbackEnabledType', 'interfaceAddress', ] eapi = pyeapi.connect(transport='https', username=username, password=password, host=device, return_node=False) interfaces = eapi.execute(['show interfaces'])['result'][0]['interfaces'] if DEBUG: return interfaces device_obj = Device.objects.get(address=device) for interface in interfaces: #remove some fields from the data interfaces[interface] = {k: v for k,v in interfaces[interface].iteritems() if k not in removed_fields} # replace the epoch time stamp with a datetime object try: temp = datetime.fromtimestamp(interfaces[interface]['lastStatusChangeTimestamp'], tz=pytz.utc) interfaces[interface]['lastStatusChangeTimestamp'] = temp except KeyError: pass try: #>> > "Member of Port-Channel26".split()[-1] members = interfaces[interface].pop('interfaceMembership').split()[-1] except KeyError: members = None name = interfaces[interface].pop('name') interface_obj, created = Interface.objects.update_or_create(device=device_obj, name=name, defaults=interfaces[interface]) if members: for member in members: if 'Peer' not in member: try: member_interface_obj = Interface.objects.get(device=device_obj, name=member) interface_obj.member = member_interface_obj interface_obj.update() except ObjectDoesNotExist: # depending the order of the interfaces we get members before having the parents in the db pass
#!/usr/bin/env python from __future__ import unicode_literals, print_function import pyeapi from getpass import getpass from my_funcs import yaml_load_devices devices = yaml_load_devices() password = getpass() for _, device_dict in devices.items(): device_dict["password"] = password connection = pyeapi.connect(**device_dict) device = pyeapi.client.Node(connection) output = device.enable(["show ip route"]) result = output[0]["result"] routes = result["vrfs"]["default"]["routes"] for route, data in routes.items(): print("-" * 10) print(route) if data["routeType"] == "connected": print("routeType is", data["routeType"]) print("-" * 10) print() else: print("routeType is", data["routeType"]) print("Next hop is", data["vias"][0]["nexthopAddr"]) print("-" * 10) print()
#!/usr/bin/env python import pyeapi connection = pyeapi.connect(host='192.168.1.16') output = connection.execute(['enable', 'show version']) print 'My system MAC address is', output['result'][1]['systemMacAddress']
def lldpInfo(dutslist): #************************************************************************ #The below code will grab lldp info from all DUTs in json format and refine it and #it will consolidate all the lldp information into a single dictionary tempDictOfConnections = [] #The below try and except block will handle errors due to eAPI not enabled on one of the DUT for i in xrange(0, len(dutslist)): try: #Using Python eAPi for getting outputs in json format conn = pyeapi.connect(host=dutslist[i], transport='https') temp = conn.execute(['show lldp neighbors']) #print temp allneighbors = temp['result'][0]['lldpNeighbors'] #print allneighbors for j in xrange(0, len(allneighbors)): temp_diction = allneighbors[j] temp_diction['myDevice'] = str( dutslist[i]) + '.sjc.aristanetworks.com' tempDictOfConnections.append(temp_diction) #print temp_diction tempDictOfConnections = tempDictOfConnections[:-1] #print tempDictOfConnections except pyeapi.eapilib.ConnectionError as e: print "\n[Please Wait]: eApi is not enabled on one of your devices namely:<-- " + dutslist[ i] + "-->. Hold on while we do that for you \n" reachabilityFlag = enableEapi( dutslist[i] ) #The return flag '1' is used to skip that device since it was not reachable in first place. If flag=0, then, we can do the below if reachabilityFlag == 1: continue else: try: #Same as above: Using Python eAPi for getting outputs in json format conn = pyeapi.connect(host=dutslist[i], transport='https') temp = conn.execute(['show lldp neighbors']) #print temp allneighbors = temp['result'][0]['lldpNeighbors'] #print allneighbors for j in xrange(0, len(allneighbors)): temp_diction = allneighbors[j] temp_diction['myDevice'] = str( dutslist[i]) + '.sjc.aristanetworks.com' tempDictOfConnections.append(temp_diction) #print temp_diction tempDictOfConnections = tempDictOfConnections[:-1] #print tempDictOfConnections except: print "[ERROR] Enabling eApi automatically failed. Please enable eApi manually on " + dutslist[ i] + " by doing 'management api http-commands' --> 'no shut' and then rerun the script" print "* Script Complete!" sys.exit(1) #************************************************************************ #The below code will remove the duplicates from the grand dictionary such that one connection shows up only once. The duplicates are marked as key=temp and value=NULL for i in xrange(0, len(tempDictOfConnections)): tempvar = tempDictOfConnections[ i] #Storing each dictionary in one temp variable #print tempvar #print '\n' instantaneoustempvar = [] instantaneoustempvar = [ tempvar['neighborDevice'], tempvar['neighborPort'] ] tempvar['neighborDevice'] = tempvar['myDevice'] tempvar['neighborPort'] = tempvar['port'] tempvar['myDevice'] = instantaneoustempvar[0] tempvar['port'] = instantaneoustempvar[1] #print tempvar count = 0 for j in xrange(0, len(tempDictOfConnections)): if tempvar == tempDictOfConnections[j]: count = count + 1 if count == 2: tempDictOfConnections[i] = {'temp': 'Null'} #print tempDictOfConnections #************************************************************************ #The below code will remove the duplicates completely by removing dictionaries with key as temp. ALso, removing the '.sjc.aristanetworks.com' in DUT name dictionaryOfConnections = [ ] #This list will have only non-duplicate values for i in xrange(0, len(tempDictOfConnections)): if tempDictOfConnections[i].get('temp') == None: tempDictOfConnections[i]['neighborDevice'] = tempDictOfConnections[ i]['neighborDevice'].split('.')[0] tempDictOfConnections[i]['myDevice'] = tempDictOfConnections[i][ 'myDevice'].split('.')[0] try: tempDictOfConnections[i]['port'] = 'Et' + ( tempDictOfConnections[i]['port'].split('Ethernet')[1]) except: print "[ERROR]: One of your lldp neighbors is not in typical format. Read above LLDP Warning on how to fix it and then rerun the script" print "* Script Complete!" sys.exit(1) tempDictOfConnections[i]['neighborPort'] = 'Et' + ( tempDictOfConnections[i]['neighborPort'].split('Ethernet')[1]) dictionaryOfConnections.append(tempDictOfConnections[i]) #Below Code will try to consolidate interfaces in series #for i in xrange(0,len(tempDictOfConnections)): return dictionaryOfConnections
def ixiaConnectionDetailGrabber(dutslist, finalConnectionDetails): #************************************************************************ #The below code will grab lldp info from all DUTs in json format and refine it and #it will consolidate all the lldp information into a single dictionary #print finalConnectionDetails ixialist = [] for i in xrange(0, len(dutslist)): try: #Using Python eAPi for getting outputs in json format conn = pyeapi.connect(host=dutslist[i], transport='https') temp = conn.execute(['show interfaces status connected']) #print temp allconnections = temp['result'][0]['interfaceStatuses'] #print allconnections listofconnections = allconnections.keys() #print listofconnections #Removing management and port-channel interfaces from list for k in xrange(0, len(listofconnections)): #print listofconnections[k] if 'Management' in listofconnections[ k] or 'Port-Channel' in listofconnections[ k] or '.' in listofconnections[k]: listofconnections[k] = None #print listofconnections[k] #Removing lldp interfaces from ixia interfaces for j in xrange(0, len(finalConnectionDetails)): #print finalConnectionDetails[i] if finalConnectionDetails[j][ 'neighborDevice'] or finalConnectionDetails[j][ 'myDevice'] == dutslist[i]: if finalConnectionDetails[j]['neighborDevice'] == dutslist[ i]: for k in xrange(0, len(listofconnections)): if listofconnections[k] == ( 'Ethernet' + finalConnectionDetails[j] ['neighborPort'].split('Et')[1]): listofconnections[k] = None if finalConnectionDetails[j]['myDevice'] == dutslist[i]: for k in xrange(0, len(listofconnections)): if listofconnections[k] == ( 'Ethernet' + finalConnectionDetails[j] ['port'].split('Et')[1]): listofconnections[k] = None #print listofconnections #Makes a dictionary containing the DUT name and the Ixia ports onlyixiaconnections = [] for k in xrange(0, len(listofconnections)): ixiadict = {} if listofconnections[k] != None: onlyixiaconnections.append(listofconnections[k]) ixiadict['neighborDevice'] = dutslist[i] ixiadict['neighborPort'] = ( 'Et' + listofconnections[k].split('Ethernet')[1]) #print listofconnections[k] ixiadict['myDevice'] = 'Ixia' #+'_'+str(randint(0,100)) ixiadict['port'] = 'unknown' ixialist.append(ixiadict) #print onlyixiaconnections except: print "[MESSAGE]: Skipping " + dutslist[ i] + " from Ixia connection calculation as well since it is unreachable" continue #print ixialist return ixialist
def connect_to(self, host='localhost', transport='https', port='443', username='******', password='******', alias=None, enablepwd=None, autorefresh=True): """This is the cornerstone of all testing. The Connect To keyword accepts the necessary parameters to setup an API connection to your node. Example: | Connect To | host=192.0.2.50 | transport=http | port=80 | username=myUser | password=secret | | Connect To | host=192.0.2.51 | username=myUser | password=secret | This function returns a connection index, which can be used to change connections during a test suite. Example: | ${switch1}= | Connect To | host=192.0.2.51 | username=myUser | password=secret | You can confirm which interface eAPI is listening on by running: | veos-node>show management api http-commands | *Enabled: Yes* | *HTTPS server: running, set to use port 443* | HTTP server: shutdown, set to use port 80 | VRF: default | Hits: 28 | Last hit: 2128 seconds ago | Bytes in: 1547 | Bytes out: 283966 | Requests: 1 | Commands: 1 | Duration: 0.055 seconds | User Hits Bytes in Bytes out Last hit | ----------- ---------- -------------- --------------- ---------------- | admin 1 1547 283966 2128 seconds ago | | URLs | --------------------------------------- | *Management1 : https://192.0.2.50:443* You can confirm connectivity by firing up a browser and point it to https://<my_url>:<my_port>/command-api If you are new to eAPI see the Arista EOS Central article, [https://eos.arista.com/arista-eapi-101|Arista eAPI 101] """ host = str(host) transport = str(transport) port = int(port) username = str(username) password = str(password) if alias: alias = str(alias) try: client = pyeapi.connect( host=host, transport=transport, username=username, password=password, port=port) client_node = pyeapi.client.Node(client) client_node.autorefresh = autorefresh client_node.enable_authentication(enablepwd) conn_indx = self._connection.register(client_node, alias) except Exception as e: raise e # Always try "show version" when connecting to a node so that if # there is a configuration error, we can fail quickly. try: ver = self._connection.current.enable( ['show version'])[0]['result'] mesg = "Created connection to {}://{}:{}@{}:{}/command-api: "\ "model: {}, serial: {}, systemMAC: {}, version: {}, "\ "lastBootTime: {}".format( transport, username, '****', host, port, ver['modelName'], ver['serialNumber'], ver['systemMacAddress'], ver['version'], ver['bootupTimestamp']) logger.write(mesg, 'INFO', False) except Exception as e: raise e self.connections[conn_indx] = dict(conn=client, node=client_node, index=conn_indx, transport=transport, host=host, username=username, password=password, port=port, alias=alias, autorefresh=autorefresh) return conn_indx
with open("hosts.yaml", "r") as host_file: hosts = yaml.load(host_file, Loader=yaml.FullLoader) # print(hosts) with open("config.yaml", "r") as config_file: cfg = yaml.load(config_file, Loader=yaml.FullLoader) # print(cfg) username = cfg['defaults']['username'] password = cfg['defaults']['password'] protocol = cfg['defaults']['protocol'] connection = pyeapi.connect(host=hosts['vEOS-LSW01']['host'], transport=protocol, username=username, password=password) node = pyeapi.client.Node(connection) ######################################## # pp(node.api('bgp').get()) # # ADD VLANS TAKEN FROM Interface Vxlan1 CONFIG # # vlans = node.api('interfaces').getall()['Vxlan1']['vlans'].keys() # print(vlans) # for vlan in vlans: # node.api('vlans').create(vlan) # node.api('vlans').set_name(vlan, name=f"TEST_{vlan}") # # pp(node.api("vlans").getall())
import pyeapi br = pyeapi.connect(host='192.168.10.1', username='******', password='******') print br.execute('show version')
if user_tags.issubset(host_tags): snapshot_dict[host] = merge_dict(snapshot_dict[host], { 'username': block['username'], 'password': block['password'], }) return snapshot_dict if __name__ == '__main__': snapshot_job = build_snapshot_job(config_file) result_list = list() for ip in snapshot_job: conn = pyeapi.connect(host=ip, transport='https', username=snapshot_job[ip]['username'], password=snapshot_job[ip]['password']) try: results = conn.execute(snapshot_job[ip]['commands'], encoding='text')['result'] except Exception as e: print('ERROR: Failed to execute command on %s.' % ip) print(e) else: zip_results = zip(snapshot_job[ip]['commands'], results) for command, result in zip_results: result_list.append({ 'ip': ip, 'command': command, 'result': result['output'] }) try:
type=str, help='Redis key name to which command output should be written') parser.add_argument('-r', dest='redishost', type=str, default='redishost', help='Hostname of redis server') args = parser.parse_args() with open(args.config_file, 'r') as fh: config = yaml.load(fh.read()) r = redis.Redis(args.redishost) for host, conf in config['switches'].iteritems(): print 'Connecting to switch: %s' % host redis_key = 'status:switch:%s' % host switch = pyeapi.connect(host=host, username=conf['username'], password=conf['password'], return_node=True) rv = switch.enable([args.command], encoding='text') string_table = rv[0]['result']['output'] print string_table r.hset( redis_key, args.key, json.dumps({ 'timestamp': datetime.datetime.now().isoformat(), 'val': string_table }))