def setHostname(host_ip): hostname = "veos-oci-" + host_ip.replace('.', '-') print("Setting hostname to " + hostname) switch = Server("https://*****:*****@" + host_ip + "/command-api") success = False try: response = switch.runCmds(1, [ "enable", "configure", "hostname " + hostname, "ip name-server vrf default 8.8.8.8", "daemon TerminAttr" + "exec /usr/bin/TerminAttr -ingestgrpcurl=162.210.129.23:9910 -taillogs -ingestauth=key," + "management api http-commands", "protocol http", "interface loopback 0", "ip address " + host_ip + "/32", "no shutdown" ]) print("configuration successful") success = true except: print("Did not connect, waiting 5 seconds") sleep(5) response = switch.runCmds(1, [ "enable", "configure", "hostname " + hostname, "ip name-server vrf default 8.8.8.8", "interface loopback 0", "ip address " + host_ip + "/32", "no shutdown" ]) return hostname
def getEAPIData(self, ip): if self.__options.verbosity > 1: print("trying to fetch {} via eapi".format(ip), flush=True) try: uri = "https://{}:{}@{}:443/command-api".format( self.__options.eapiUser, self.__options.eapiPassword, ip) switch = Server(uri, transport=self.transport) try: response = switch.runCmds( 1, ['enable', 'show hostname', 'show snmp mib ifmib ifindex']) hBase = 1 iBase = 2 except: response = switch.runCmds( 1, ['show hostname', 'show snmp mib ifmib ifindex']) hBase = 0 iBase = 1 host = {'hostname': response[hBase]['hostname'], 'interfaces': {}} # for the cache to work right in need to re-index the result set inverted for iface, index in response[iBase]['ifIndex'].items(): host['interfaces'][str(index)] = iface # save the cache self.__cache[ip] = host except Exception as e: if self.__options.verbosity > 1: print("getEAPIData had a failure fetching from {}".format(ip)) return (False, None) return (True, host)
def main(): parser = argparse.ArgumentParser() parser.add_argument( "-u", "--user", type=str, default="", help="specify a username", required=True) parser.add_argument( "-s", "--session", type=str, default="", help="specify config session name", required=True) parser.add_argument( "-f", "--file", type=str, default="", help="specify a file with static MACs to apply", required=True) parser.add_argument( "-d", "--device", type=str, default="", help="specify an EOS device which static MACs are to applied", required=True) parser.add_argument( "-p", "--passwd", type=str, default="", help="for passing password interactively", required=False) parser.add_argument( "-r", "--remove", action='store_true', help="to remove applied static mac addresses", required=False) args = parser.parse_args() n = 4 rand = ''.join(random.choices(string.ascii_uppercase + string.digits, k = n)) session = args.session + "-" + rand file = args.file hostname = args.device remove = args.remove user = args.user if len(args.passwd) > 0: passwd = args.passwd else: passwd = '***REMOVED***' _create_unverified_https_context = ssl._create_unverified_context ssl._create_default_https_context = _create_unverified_https_context with open(file, "r") as current_file: macaddresses = current_file.readlines() device = Server('https://{}:{}@{}/command-api'.format(user, passwd, hostname)) try: for mac in macaddresses: #mac addresses in file should have format aa:aa:aa:aa:aa:aa.vlan#.interface# # bits = mac.split(".") macaddr = bits[0] vlan = bits[1] intf = bits[2] if remove == True: result = device.runCmds(1, ['enable', 'configure session {0}'.format(session), 'no mac address-table static {0}'.format(macaddr) + ' vlan {0}'.format(vlan) + ' interface {0}'.format(intf)]) else: result = device.runCmds(1, ['enable', 'configure session {0}'.format(session), 'mac address-table static {0}'.format(macaddr) + ' vlan {0}'.format(vlan) + ' interface {0}'.format(intf)]) result2 = device.runCmds(1, ['enable', 'configure session {0}'.format(session) + ' commit']) except: print("something went wrong, check password\n\n")
def ta_shut5(): ip = '192.168.11.5' url = 'http://%s:%s@%s/command-api' % (user, passwd, ip) ss = Server(url) ss.runCmds( 1, ['enable', 'configure terminal', 'daemon TerminAttr', 'shutdown']) pp(ss.runCmds(1, ['enable', 'show daemon TerminAttr']))
def main(): argument_spec = dict( vlan_id=dict(required=True), vlan_name=dict(), host=dict(), username=dict(required=True), password=dict(required=True), port=dict(required=False), transport=dict(choices=['http', 'https'],required=False) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) vlan_id = module.params['vlan_id'] vlan_name = module.params['vlan_name'] host = str(module.params['host']) username = module.params['username'] password = module.params['password'] port = int(module.params['port']) transport = module.params['transport'] conn = Server("https://%s:%s@%s/command-api" %(username, password, host)) list_cmds = [ "enable", "configure" ] list_cmds.append("vlan %s" %(vlan_id)) list_cmds.append("name %s" %(vlan_name)) conn.runCmds(1, list_cmds, "json") module.exit_json(msg="Vlan created successfully")
def main(): #Disable SSL self-signed verification ssl._create_default_https_context = ssl._create_unverified_context parser = argparse.ArgumentParser() parser.add_argument('--user', default='admin', dest='user') parser.add_argument('--password', dest='passwd') parser.add_argument('--csvinfile', dest='csvinfile') parser.add_argument('--method', default='https', dest='method', choices=['http', 'https']) args = parser.parse_args() user = args.user passwd = args.passwd method = args.method csvinfile = args.csvinfile if len(sys.argv[1:]) == 0: parser.print_help() parser.exit() with open (csvinfile, 'r') as rf: reader = csv.DictReader(rf) for row in reader: sw = row['switch'] cmdapi = Server("{}://{}:{}@{}/command-api".format(method,user,passwd,sw)) cmdapi.runCmds(1,["enable", "configure", "no daemon TerminAttr"]) shdaemon = cmdapi.runCmds(1,["show daemon"]) #Verify daemon has been removed from each switch print(shdaemon[0]['daemons'])
def acl(user, passwd, ip): url = 'http://%s:%s@%s/command-api' % (user, passwd, ip) ss = Server(url) ss.runCmds(1, [ 'enable', 'configure terminal', 'ip access-list jason', '10 permit ip 192.168.0.0/24 any', '20 permit ip 172.16.0.0/12 any', '30 permit ip 0.0.0.0/0 any', '40 permit ip any any' ])
def ta_shut(): for ip in ips: url = urls(ip) ss = Server(url) ss.runCmds(1, [ 'enable', 'configure terminal', 'daemon TerminAttr', 'no shutdown' ]) pp(ss.runCmds(1, ['enable', 'show daemon TerminAttr']))
def remove_acl(ip_list): adjacency_list = find_topology(ip_list) for ip in adjacency_list.keys(): switch_cli = Server( "http://*****:*****@"+ip+"/command-api" ) configure_acl_response = switch_cli.runCmds( 1, ["enable","configure terminal","no ip access-list trace",]) for interface in adjacency_list[ip].values(): configure_acl_interface_response = switch_cli.runCmds( 1, ["enable","configure terminal", "interface "+interface, "no ip access-group trace in", "end"])
def addACL(ipaddr, name, rules): # add new acl commandsToRun = ["enable", "configure"] aclname = "ip access-list " + name commandsToRun += [aclname] commandsToRun += rules urlString = "https://{}:{}@{}/command-api".format(username, password, ipaddr) # 1 switchReq = Server(urlString) # 2 switchReq.runCmds(1, commandsToRun) # 3
def main(): for switch in switches: #SESSION SETUP FOR eAPI TO DEVICE url = "https://%s:%s@%s/command-api" % (user, passwd, switch) ss = Server(url) #CONNECT TO DEVICE hostname = ss.runCmds(1, ['enable', 'show hostname'])[1]['hostname'] running_config = ss.runCmds(1, ['enable', 'show running-config'], 'text')[1]['output'] with open(hostname, 'w') as f: f.write(running_config)
def main(): parser = argparse.ArgumentParser(description='Location,') parser.add_argument('-location', choices=['dc1','dc2'], help='Enter the colo location dc1|dc2') parser.add_argument('-new_extension', help='Enter name of extension to be added') parser.add_argument('-old_extension', help='Enter name of extension to be removed') parser.add_argument('--scp', action='store_true', help='SCP new extension to arista device. System exit once finished') args = parser.parse_args() if args.location == 'dc1': hostlist = arista_devices_dc1() elif args.location == 'dc2': hostlist = arista_devices_dc2() #---------------------------------------------------------------- # Configuration section #---------------------------------------------------------------- EAPI_USERNAME = os.getenv("USER") EAPI_PASSWORD = get_user_info() EAPI_METHOD = 'https' # Disable ssh HTTPS certificates checking by default disable_https_cert() if args.scp: scp(hostlist,EAPI_USERNAME,EAPI_PASSWORD,args.new_extension) # configuration loop for host in hostlist: switch = Server( '%s://%s:%s@%s/command-api' % ( EAPI_METHOD, EAPI_USERNAME, EAPI_PASSWORD, host ) ) # uninstall extension try: rc = switch.runCmds( 1, [ 'no extension %s' %args.old_extension ]) print( 'Host configured: %s extension removed' % ( host ) ) except: print "Extension %s not installed on %s" %(args.old_extension, host) # Pause 1 second between extension being uninstalled and removed time.sleep(1) # remove uninstalled extension from extension namespace try: rc = switch.runCmds( 1, [ 'delete extension:%s' %args.old_extension ]) except: print "Extension %s couldn't be deleted" %args.old_extension # New extension logic try: rc = switch.runCmds( 1, [ 'copy flash:%s extension:%s' %(args.new_extension,args.new_extension), 'extension %s' %args.new_extension ]) print( 'Host configured: %s extension added' % ( host ) ) except: print "Extension %s already installed on %s" %(args.new_extension, host) next
def main(): switch = Server('https://%s:%s@%s/command-api' % (PASSWORD, USERNAME, SWITCH_IP)) response = switch.runCmds(1, ['show lldp neighbors']) neighborInfo = response[0]['lldpNeighbors'] for i in neighborInfo: localIntf = i['port'] intfDesc = '*** Link to %s(%s)' % (i['neighborDevice'], i['neighborPort']) rc = switch.runCmds(1, [ 'enable', 'configure', 'interface %s' % (localIntf), 'description %s' % (intfDesc) ])
def reroute_traffic(): try: if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)): ssl._create_default_https_context = ssl._create_unverified_context switch = Server("https://<username>:<password>@127.0.0.1/command-api") check_monitor = switch.runCmds(1, ["show monitor connectivity"]) for monitor in check_monitor: nei_lst = [] for k, v in monitor['hosts'].iteritems(): if v['packetLoss'] > 0: syslog.openlog( 'Next-Hop {} is unreachable, lowering the local-preference\n' .format(k), 0, syslog.LOG_LOCAL4) syslog.syslog( '%%PROB-FAILED-6-LOG: Log msg: Next-Hop {} is unreachable, lowering the local-preference' .format(v['ipAddr'])) print( "We are expiriancing packet loss on device ip {} \nchanging the local preference to 50" .format(v['ipAddr'])) switch.runCmds(1, [ "enable", " configure", "router bgp {}".format( get_asn()), "neighbor {} import-localpref 50".format(v['ipAddr']) ]) print("route for neighbor {} changed local-pref to 50". format(v['ipAddr'])) elif v['packetLoss'] == 0: syslog.openlog( 'Next-Hop {} is reachable, removing the local-preference config\n' .format(v['ipAddr']), 0, syslog.LOG_LOCAL4) syslog.syslog( '%%PROB-SUCCESS-6-LOG: Log msg: Next-Hop {} is reachable, removing the local-preference config' .format(v['ipAddr'])) print( "Neighbor {} is reachable changing the local preference to default" .format(v['ipAddr'])) switch.runCmds(1, [ "enable", " configure", "router bgp {}".format( get_asn()), "no neighbor {} import-localpref 50".format( v['ipAddr']) ]) else: print("Cannot locate packet loss value") except KeyboardInterrupt as e: print "Ok Ok, I'm breaking.." except IOError as e: print e
def extInstall(switch, filename, protocol, user, passwd): sw = switch.split(',') for a in sw: cmdapi = Server("{}://{}:{}@{}/command-api".format( protocol, user, passwd, a)) #Copy extension from /tmp to extension, then install, and write to memory cmdapi.runCmds(1, [ "enable", "configure", "copy file:/tmp/" + filename + " extension:", "extension " + filename ]) cmdapi.runCmds(1, [ "enable", "configure", "copy installed-extensions boot-extension", "wr mem" ])
def eApiShowInterfaces(): switch = Server(commandApiUrl) response = switch.runCmds( 1, ["show interfaces"]) if (request.query.callback): return directFlowJsonp(request) else: return json.dumps(eApiDirectFlow(), indent=4, sort_keys=True)
def GetVersion(x): verLoc = 19 IP = "10.0.0." + str(x) switch = Server("https://" + ScriptUser + ":" + ScriptPass + "@" + IP + "/command-api") # Results in Host Unreach never happening, but [ . ] means same thing # without waiting socket.setdefaulttimeout(3) try: response = switch.runCmds(1, ["show version"]) except socket.error, ERR: ErrorCode = ERR[0] if ErrorCode == errno.ECONNREFUSED: win.addstr( x, verLoc - 6, " [ Err " + str(ErrorCode) + ": No eAPI ] ") refresh() elif ErrorCode == errno.EHOSTUNREACH: # Never hit with lower socket timeout win.addstr( x, verLoc, "Err " + str(ErrorCode) + ": Pwr off or Aboot ] ") refresh() elif ErrorCode == errno.ECONNRESET: win.addstr(x, verLoc, "Err " + str(ErrorCode) + ": Con RST ] ") refresh()
def show_vlans(): for switch in switches: urlString = "http://{}:{}@{}/command-api".format(switchusername, switchpassword, switch) switchReq = Server( urlString ) response = switchReq.runCmds( 1, ["show vlan"] ) print "Showing the vlans on %s" % (switch) print json.dumps(response, indent=4)
def main(): #SESSION SETUP FOR eAPI TO DEVICE url = "https://%s:%s@%s/command-api" % (user, passwd, switch) ss = Server(url) #CONNECT TO DEVICE hostname = ss.runCmds( 1, ['enable', 'show hostname' ])[1]['hostname'] print 'Hostname is '+hostname
def test_get_device_status_good(self): """ Test get_device_status happy path """ from mock import MagicMock from jsonrpclib import Server device = dict(self.device) sh_ver = dict(self.sh_ver) # Arbitrary test valuse model = "Monkey-bot" timestamp = 1408034881.09 sh_ver['modelName'] = model sh_ver['bootupTimestamp'] = timestamp response = [] response.append(sh_ver) device['eapi_obj'] = Server('https://*****:*****@10.10.10.11:443/command-api') device['eapi_obj'].runCmds = MagicMock(return_value=response) #response = [] #response.append({}) #response[0][u'interfaceStatuses'] = self.int_status app.get_device_status(device) self.assertEqual(device['modelName'], model) self.assertEqual(device['bootupTimestamp'], timestamp)
def main(args): '''Do Stuff. ''' log("Entering {0}.".format(sys._getframe().f_code.co_name), level='DEBUG') log("Started up successfully. Entering main loop...") switch = Server("{0}://{1}:{2}@{3}:{4}/command-api"\ .format(PROTOCOL, USERNAME, PASSWORD, HOSTNAME, PORT)) interfaces = {} while True: interfaces = get_interfaces(switch) response = switch.runCmds(1, [ "show interfaces {0} transceiver".format(', '.join( interfaces.keys())), "show version" ]) dominfo = response[0][u'interfaces'] uptime = int(response[1][u'bootupTimestamp']) for interface in interfaces.keys(): check_interfaces(uptime, str(interface), interfaces[interface], dominfo[interface]) log("---sleeping for {0} seconds.".format(args.poll_interval), level='DEBUG') time.sleep(args.poll_interval)
def add_vlans(): for switch in switches: for vlanlist in vlans: urlString = "http://{}:{}@{}/command-api".format(switchusername, switchpassword, switch) switchReq = Server( urlString ) response = switchReq.runCmds( 1, ["enable", "configure", "vlan" +" "+ str(vlanlist)] ) print "adding vlans %s" % (vlanlist)
def main(): parser = argparse.ArgumentParser(description='Location,Ipaddress') parser.add_argument('-location', choices=['dc1','dc2'], help='Enter the colo location dc1|dc2') parser.add_argument('-ip', help='Enter switch ip address') args = parser.parse_args() if args.location == 'dc1': hostlist = arista_devices_dc1() elif args.location == 'dc2': hostlist = arista_devices_dc2() disable_https_cert() #---------------------------------------------------------------- # Configuration section #---------------------------------------------------------------- #-------------------Configuration - MUST Set ------------------------ EAPI_USERNAME = os.getenv("USER") EAPI_PASSWORD = get_user_info() # http or https method EAPI_METHOD = 'https' for host in hostlist: switch = Server( '%s://%s:%s@%s/command-api' % ( EAPI_METHOD, EAPI_USERNAME, EAPI_PASSWORD, host ) ) rc = switch.runCmds( 1, [ 'enable', 'configure', 'interface Vxlan1', 'vxlan flood vtep add %s' % args.ip ] ) print( 'Host configured: %s' % ( host ) )
def main(args): ''' main ''' parser = OptionParser() parser.add_option('-u', '--username', default='eapi', help='username') parser.add_option('-p', '--password', default='', help='password') parser.add_option('-P', '--port', default='8543', help='port') parser.add_option('-D', '--debug', action='store_true', help='debug') options, args = parser.parse_args() for switch in args: url = "https://{0}:{1}@{2}:{3}/command-api".format( options.username, options.password, switch, options.port ) request = Server(url) response = request.runCmds(1, ["show interfaces"] ) if options.debug: print json.dumps(response, indent=4, sort_keys=True) interfaces = sorted(response[0]['interfaces'].keys()) print "Switch {0} interfaces:".format(switch) print "{:20} {:<20} {:<20}".format("Interface", "inOctets", "outOctets") for inf in interfaces: data = response[0]['interfaces'][inf] if 'interfaceCounters' in data: print "{:20} {:<20} {:<20}".format( inf, data['interfaceCounters']['inOctets'], data['interfaceCounters']['outOctets'] ) print
def get_hostname(ip_list): ip_to_hostname = {} for ip in ip_list: switch_cli = Server( "http://*****:*****@"+ip+"/command-api" ) response_hostname = switch_cli.runCmds( 1, ["show hostname"]) ip_to_hostname[ip] = response_hostname[0]["hostname"] return ip_to_hostname
def configure_acl(ip_list,vtep_list,udp_source_port): adjacency_list = find_topology(ip_list) for ip in adjacency_list.keys(): switch_cli = Server( "http://*****:*****@"+ip+"/command-api" ) configure_acl_response = switch_cli.runCmds( 1, ["enable","configure terminal","ip access-list trace", "statistics per-entry", "10 permit udp host "+vtep_list[0]+" eq "+udp_source_port+" host "+vtep_list[1], "20 permit udp host "+vtep_list[1]+" eq "+udp_source_port+" host "+vtep_list[0], "30 permit ip any any"]) for interface in adjacency_list[ip].values(): configure_acl_interface_response = switch_cli.runCmds( 1, ["enable","configure terminal", "interface "+interface, "ip access-group trace in", "end"]) switch_acl_counters_old = get_statistics(ip_list) return switch_acl_counters_old
def openconnexion(device, username, password, cde): global commandesAfterError switch = Server("http://%s:%s@%s/command-api" % (username, password, device)) try: # result = switch.runCmds(version = 1, cmds = cde) result = switch.runCmds(version="latest", cmds=cde) # Format the result if result is not empty if result != None: data = {} for index in range(0, len(result)): data.update({cde[index].replace(" ", ""): result[index]}) writeData('devices/' + device, data) except AppError as err: code = err.args[0][0] error = err.args[0][1] if code == 1000: erreurCde = error.split("'")[1] commandesAfterError.remove(erreurCde) openconnexion(device, username, password, commandesAfterError) except: deviceNotConnected.append(device) data = {} writeData('devices/' + device, data)
def test_get_device_status_good(self): """ Test get_device_status happy path """ from mock import MagicMock from jsonrpclib import Server device = dict(self.device) sh_ver = dict(self.sh_ver) # Arbitrary test valuse model = "Monkey-bot" timestamp = 1408034881.09 sh_ver['modelName'] = model sh_ver['bootupTimestamp'] = timestamp response = [] response.append(sh_ver) device['eapi_obj'] = Server( 'https://*****:*****@10.10.10.11:443/command-api') device['eapi_obj'].runCmds = MagicMock(return_value=response) #response = [] #response.append({}) #response[0][u'interfaceStatuses'] = self.int_status app.get_device_status(device) self.assertEqual(device['modelName'], model) self.assertEqual(device['bootupTimestamp'], timestamp)
def main(): endpoint_list = [] pool_size = int(netblock.size) jobs = multiprocessing.Queue() results = multiprocessing.Queue() pool = [ multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size) ] for p in pool: p.start() for host in netblock: jobs.put(str(host)) for p in pool: jobs.put(None) for p in pool: p.join() while not results.empty(): ip = results.get() endpoint_list.append(ip) listofendpoints = [] for live_endpoint in endpoint_list: try: #SESSION SETUP FOR eAPI TO DEVICE url = "https://%s:%s@%s/command-api" % (user, passwd, str(live_endpoint)) ss = Server(url) #CONNECT TO DEVICE hostname = ss.runCmds(1, ['enable', 'show hostname'])[1]['hostname'] version = ss.runCmds(1, ['enable', 'show version'])[1] modelnumber = version['modelName'] serial = version['serialNumber'] jsonlist = {hostname: [modelnumber, serial]} listofendpoints.append(jsonlist) except: print 'Failure to connect to -- ' + live_endpoint pprint(listofendpoints)
def show_vlans(): for switch in switches: urlString = "http://{}:{}@{}/command-api".format( switchusername, switchpassword, switch) switchReq = Server(urlString) response = switchReq.runCmds(1, ["show vlan"]) print "Showing the vlans on %s" % (switch) print json.dumps(response, indent=4)
def getCurrentImage(switchuser, switchpass, ssh_host): command_string = "show boot-config" urlString = "https://{}:{}@{}/command-api".format(switchuser, switchpass, ssh_host) switchReq = Server(urlString) response = switchReq.runCmds( 1, ["enable", command_string] ) responsePr = response [1]["softwareImage"] currentimage=responsePr.split('/')[1] return currentimage
def csvout(): today = datetime.date.today() ssl._create_default_https_context = ssl._create_unverified_context input = str( raw_input( "What switch, or switches, would you like to connect to separated by a comma: " )) host = input.split(",") while True: try: prot = str( raw_input( "Which eAPI protocol do you want to use [http or https]? ") ) break except ValueError: print("Please enter http or https") continue user = str(raw_input("Username: "******"%s://%s:%s@%s/command-api" % (prot, user, passwd, a)) bgpsumm = cmdapi.runCmds(1, ["show ip bgp summary"]) for b in bgpsumm[0]['vrfs']['default']['peers']: state = bgpsumm[0]['vrfs']['default']['peers'][b][ 'peerState'] prfxrcvd = bgpsumm[0]['vrfs']['default']['peers'][b][ 'prefixReceived'] asnum = bgpsumm[0]['vrfs']['default']['peers'][b]['asn'] updown = bgpsumm[0]['vrfs']['default']['peers'][b][ 'upDownTime'] # Write to CSV File writer.writerow({ 'Switch ID': a, 'Peers': b, 'BGP State': state, 'Prefix(es) Received': prfxrcvd, 'AS Number': asnum, 'Up/Down Status': updown }) except: sys.exit(2)
def runCommand(user, password, address, port, commands, output="json", protocol="https"): """ Function to connect to EAPI interface on a switch and send commands to it, the routine will return the output of each command in JSON format by default. user - username to access switch with, requires correct privledge level to run the required commands password - password for above user address - ip or url for target switch port - tcp port to access the EAPI interface, normally 443 commands - list of commands to pass to the switch option - protocol to use for EAPI session http, https, or local (unix sockets) output - output format to be return by the EAPI options are txt or json """ # Work arround for ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833) # import ssl ssl._create_default_https_context = ssl._create_unverified_context if protocol == "http": #Connect to Switch via HTTP eAPI switch = Server("http://" + user + ":" + password + "@" + address + ":" + str(port) + "/command-api") elif protocol == "https": #Connect to Switch via HTTPS eAPI switch = Server("https://" + user + ":" + password + "@" + address + ":" + str(port) + "/command-api") elif protocol == "local": # Connect to Switch via Unix Socket EAPI_SOCKET = 'unix:/var/run/command-api.sock' switch = Server(EAPI_SOCKET) # capture Connection problem messages: try: response = switch.runCmds(1, commands, output) jsonrpclib.history.clear() except socket.error, error: error_code = error[0] if error_code == errno.ECONNREFUSED: # Raise exception if connection is refused by switch con_error = str("[Error:" + str(error_code) + "] Connection Refused!(eAPI not configured?)") elif error_code == errno.EHOSTUNREACH: # Raise exception if switch is unreachable from host con_error = str("[Error:" + str(error_code) + "] No Route to Host(Switch powered off?)") elif error_code == errno.ECONNRESET: # Raise exception if connection is refset by the switch con_error = str("[Error:" + str(error_code) + "] Connection RST by peer (Restart eAPI)") elif error_code == 8: # Raise exception if switch hostname cannot be resolved in DNS con_error = str( "[Error:" + str(error_code) + "] Host/Server name not resolved (Check DNS or Host File)") else: # Unknown error - report error number and error string (should capture all) con_error = str("[Error:" + str(error_code) + "] " + error[1]) return con_error
def get_asn(): if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)): ssl._create_default_https_context = ssl._create_unverified_context switch = Server("https://<username>:<password>@127.0.0.1/command-api") get_asn = switch.runCmds(1, ["show ip bgp summary"]) for asn in get_asn: local_asn = asn['vrfs']['default']['asn'] return local_asn
class Buildit(): def __init__(self, ipadd): self.ipadd = ipadd self.url = f'http://*****:*****@{self.ipadd}/command-api' self.ss = Server(self.url) def cmds(self, cmd): response = self.ss.runCmds(1, [cmd]) return response
def shutdown_port(m, n): try: switch = Server("https://*****:*****@" + n + "/command-api") response = switch.runCmds(1, [ "enable", "configure", "interface " + m, "shutdown", "switchport access vlan 999", "switchport mode access" ]) except: print("Could not connect to {} to shutdown ports".format(n))
def interfaceProvisioned( switchName, interfaceName ): mySwitch = Server( "unix:/var/run/command-api.sock" ) result = mySwitch.runCmds(1, [ "enable", "show interfaces " + interfaceName] ) if result[1]["interfaces"][interfaceName]["description"] == "": exists = 0 else: exists = 1 return exists
def add_vlans(): for switch in switches: for vlanlist in vlans: urlString = "http://{}:{}@{}/command-api".format( switchusername, switchpassword, switch) switchReq = Server(urlString) response = switchReq.runCmds( 1, ["enable", "configure", "vlan" + " " + str(vlanlist)]) print "adding vlans %s" % (vlanlist)
def viewACL(ipaddr): # show all acls commandsToRun = ["enable", "show ip access-lists"] urlString = "https://{}:{}@{}/command-api".format(username, password, ipaddr) # 1 switchReq = Server(urlString) # 2 response = switchReq.runCmds(1, commandsToRun) # 3 for acl in response[1]['aclList']: if acl["readonly"] == False: pprint.pprint(acl)
def deleteACL(ipaddr, name): #remove acl commandsToRun = ["enable", "configure"] aclname = "no ip access-list " + name commandsToRun += [aclname] urlString = "https://{}:{}@{}/command-api".format(username, password, ipaddr) # 1 switchReq = Server(urlString) # 2 response = switchReq.runCmds(1, commandsToRun) # 3 print("Removed ACL: ", name) pprint.pprint(response) # 4
def get_ports(ip_to_hostname): ip_port_dict = {} all_ports = [] for ip in ip_to_hostname.keys(): switch_cli = Server( "http://*****:*****@"+ip+"/command-api" ) response_lldp = switch_cli.runCmds( 1, ["enable","show lldp neighbors"]) port_list = [] for i in response_lldp[1]["lldpNeighbors"]: if i["neighborDevice"] in ip_to_hostname.values(): port_list.append(i["port"]) if len(port_list) > 1: portchannel_interface = switch_cli.runCmds( 1, ["show interfaces "+port_list[0]+" status"]) po_n = portchannel_interface[0]["interfaceStatuses"][port_list[0]]["vlanInformation"]["vlanExplanation"][3:] port_list.append(po_n) ip_port_dict[ip] = port_list ip_port_dict["10.114.211.7"].append("Ethernet10") ip_port_dict["10.114.211.5"].append("Ethernet9") return ip_port_dict
def main(): today = getDate() print "bandwidth2csv running: ", today cvsBanner = "Port,Speed,Description,In Mbps, In %, Out Mbps, Out %" for switch in switchList: print "Processing: " + switch # create a file per switch thisFile = today + "_" + str(switch) + ".csv" data_file = open(thisFile, 'w') data_file.write(cvsBanner + "\n") # open the eAPI connection serverString = "http://" + username + ":" + password + "@" + switch + "/command-api" object = Server(serverString) # Get the current show int response = object.runCmds(1, ["enable", "show interfaces"]) # Format and print per interface temp = response[1]['interfaces'] for interface in response[1]['interfaces']: #print interface if 'hardware' in response[1]['interfaces'][interface].keys(): if response[1]['interfaces'][interface][ 'hardware'] == 'ethernet': #print "interfaceStatistics" if response[1]['interfaces'][interface][ 'interfaceStatus'] == 'connected': line = str( interface) + "," + response[1]['interfaces'][ interface]['description'] + "," + prettyBW( response[1]['interfaces'][interface] ['bandwidth']) #print(line) for key in bandwithItems: #print key, temp[interface]['interfaceStatistics'][key] line = line + "," + str( round( response[1]['interfaces'][interface] ['interfaceStatistics'][key] / 1000000, 2)) + "," + percentUtilised( response[1]['interfaces'][interface] ['interfaceStatistics'][key], response[1]['interfaces'][interface] ['bandwidth']) #print (line) data_file.write(line + "\n") data_file.close()
def find_neighbors(): #Function makes sure that each and every API is actually running on each switches and can pull with the current password. for switch in switches: urlString = "http://%s:%s@%s/command-api" % (switchusername, switchpassword, switch) switchReq = Server( urlString ) response = switchReq.runCmds( 1, ["show lldp neighbors"] ) neighborresponse = response[0]["lldpNeighbors"] nodes = neighborresponse neighborlist = [] for neighbors in nodes: iterateneighbors = neighbors['neighborDevice'] neighborlist.append(iterateneighbors) print neighborlist
def find_topology(ip_list): ip_to_hostname = get_hostname(ip_list) adjacency_list = {} for ip in ip_to_hostname.keys(): switch_cli = Server("http://*****:*****@"+ip+"/command-api") response_lldp = switch_cli.runCmds(1,["enable","show lldp neighbors"]) adjacency_list[ip] = {} #print ip for index in range(len(response_lldp[1]["lldpNeighbors"])): if (response_lldp[1]["lldpNeighbors"][index]['neighborDevice'] in ip_to_hostname.values()): if (response_lldp[1]["lldpNeighbors"][index]['neighborDevice'] in adjacency_list[ip].keys()): portchannel_interface = switch_cli.runCmds( 1, ["show interfaces "+response_lldp[1]["lldpNeighbors"][index]['port']+" status"]) po_n = portchannel_interface[0]["interfaceStatuses"][response_lldp[1]["lldpNeighbors"][index]['port']]["vlanInformation"]["vlanExplanation"][3:] adjacency_list[ip][response_lldp[1]["lldpNeighbors"][index]['neighborDevice']] = po_n else : adjacency_list[ip][response_lldp[1]["lldpNeighbors"][index]['neighborDevice']] = response_lldp[1]["lldpNeighbors"][index]['port'] elif (response_lldp[1]["lldpNeighbors"][index]['neighborDevice'] == "localhost"): adjacency_list[ip][response_lldp[1]["lldpNeighbors"][index]['neighborDevice']] = response_lldp[1]["lldpNeighbors"][index]['port'] return adjacency_list
def get_statistics(ip_list): switch_acl_counters = {} ip_to_hostname = get_hostname(ip_list) for ip in ip_list: switch_cli = Server( "http://*****:*****@"+ip+"/command-api" ) response = switch_cli.runCmds( 1, ["enable","show ip access-lists trace"]) switch_acl_counters[ip] = [] for items in response[1]["aclList"][0]["sequence"]: if "packetCount" in items["counterData"]: switch_acl_counters[ip].append(int(items["counterData"]["packetCount"])) else: switch_acl_counters[ip].append(0) return switch_acl_counters
def test_get_interfaces_good(self): """ Test get_interfaces happy path """ from mock import MagicMock from jsonrpclib import Server switch = Server('https://*****:*****@10.10.10.11:443/command-api') response = [] response.append({}) response[0][u'interfaceStatuses'] = self.int_status switch.runCmds = MagicMock(return_value=response) interfaces = app.get_interfaces(switch) self.assertEqual(interfaces, self.int_status)
def test_get_intf_counters_default(self): """ Test get_intf_counters with no interface specified """ from mock import MagicMock from jsonrpclib import Server switch = Server('https://*****:*****@10.10.10.11:443/command-api') response = [] response.append({}) response[0][u'interfaces'] = self.reference switch.runCmds = MagicMock(return_value=response) (propername, counters) = app.get_intf_counters(switch) self.assertDictEqual(counters, self.reference['Management1'])
def find_source_switch(unsorted_switch_list,source_switch,adjacency_list,source_ip): for i in range(len(unsorted_switch_list)): for switch in unsorted_switch_list: #print switch switch_cli = Server( "http://*****:*****@"+switch+"/command-api" ) response_arp = switch_cli.runCmds( 1, ["enable","show ip arp"]) arp_list = response_arp[1]["ipV4Neighbors"] interface_name = "" for num in range(len(arp_list)): if arp_list[num]["address"] == source_ip: interface_name = arp_list[num]["interface"].split(' ')[1] break nei = find_neighbor(switch,interface_name,adjacency_list) if nei == source_switch : return switch
def execute_commands(hostname,ip,commands): """ Execute commands. Args: hostname, ip, commands Return: Boolean """ try: my_headers = {'content-type': 'application/json-rpc'} switch = Server("https://"+username+":"+password+"@"+ip+"/command-api") try: response = switch.runCmds( 1, commands ) print response except Exception, e: print "Failed : %s" % str(e) return return True
def GetVersion(x): verLoc = 19 IP = "10.0.0." + str(x) switch = Server( "https://" + ScriptUser + ":" + ScriptPass + "@" + IP + "/command-api" ) # Results in Host Unreach never happening, but [ . ] means same thing # without waiting socket.setdefaulttimeout(3) try: response = switch.runCmds( 1, [ "show version" ] ) except socket.error,ERR : ErrorCode = ERR[0] if ErrorCode == errno.ECONNREFUSED: win.addstr(x, verLoc -6, " [ Err " + str(ErrorCode) + ": No eAPI ] ") refresh() elif ErrorCode == errno.EHOSTUNREACH: # Never hit with lower socket timeout win.addstr(x, verLoc, "Err " + str(ErrorCode) + ": Pwr off or Aboot ] ") refresh() elif ErrorCode == errno.ECONNRESET: win.addstr(x, verLoc, "Err " + str(ErrorCode) + ": Con RST ] ") refresh()
def main(args): """Do Stuff. """ log("Entering {0}.".format(sys._getframe().f_code.co_name), level="DEBUG") log("Started up successfully. Entering main loop...") switch = Server("{0}://{1}:{2}@{3}:{4}/command-api".format(PROTOCOL, USERNAME, PASSWORD, HOSTNAME, PORT)) interfaces = {} while True: interfaces = get_interfaces(switch) response = switch.runCmds( 1, ["show interfaces {0} transceiver".format(", ".join(interfaces.keys())), "show version"] ) dominfo = response[0][u"interfaces"] uptime = int(response[1][u"bootupTimestamp"]) for interface in interfaces.keys(): check_interfaces(uptime, str(interface), interfaces[interface], dominfo[interface]) log("---sleeping for {0} seconds.".format(args.poll_interval), level="DEBUG") time.sleep(args.poll_interval)
def getNetworks(mode): switch = Server("unix:/var/run/command-api.sock") result = switch.runCmds(1, ["show ip interface brief"], "text") result = result[0]['output'] result = result.split('\n') networks = [] for row in result: row = row.split() if len(row) > 0: # Error check for empty row if row[1] != "unassigned": # Check for assigned networks if row[1] != "IP": networks.append(row[1]) i = 0 print("-----------------------------------------") print("Network\t\tSubnet") print("-----------------------------------------") for network in networks: print(str(i) + "\t\t" + network) i += 1 var = raw_input("\nEnter the network to ping (0-" + str(len(networks) - 1) + "): ") doPing(networks[int(var)])
metric_threshold = 125000000 flows = { "keys":"ipsource,ipdestination", "value":"bytes", "n":10, "t":2 } threshold = {"metric":metric,"value":metric_threshold,"byFlow":True} for switch_ip in switch_ips: switch = Server("http://%s:%s@%s/command-api" % (username, password, switch_ip)) response = switch.runCmds(1, ["enable", "configure", "sflow source %s" % switch_ip, "sflow destination %s %s" % (sflow_ip, sflow_port), "sflow polling-interval %s" % sflow_polling, "sflow sample output interface", "sflow sample dangerous %s" % sflow_sampling, "sflow run"]) r = requests.put("http://%s:8008/flow/%s/json" % (sflow_ip, metric), data=json.dumps(flows)) r = requests.put("http://%s:8008/threshold/%s/json" % (sflow_ip, metric), data=json.dumps(threshold)) def sig_handler(signal,frame): requests.delete("http://%s:8008/flow/%s/json" % (sflow_ip, metric)) requests.delete("http://%s:8008/threshold/%s/json" % (sflow_ip, metric)) exit(0) signal.signal(signal.SIGINT, sig_handler)
def eApiIntfDirectFlow(): switch = Server(commandApiUrl) response = switch.runCmds( 1, ["show interfaces", "show directflow flows"] ) return response
def eApiDirectFlow(): switch = Server(commandApiUrl) response = switch.runCmds( 1, ["show directflow flows"] ) return response[0]['flows']
def eApiShowInterfaces(): switch = Server(commandApiUrl) response = switch.runCmds( 1, ["show interfaces"]) return response[0]
def gethostname(switch_ip): urlString = "https://{}:{}@{}/command-api".format(username, password, switch_ip) switchReq = Server( urlString ) response = switchReq.runCmds( 1, ["show hostname"] ) hostname=response[0]["hostname"] return hostname
def default_hostname(switch_ip): urlString = "https://{}:{}@{}/command-api".format(username, password, switch_ip) switchReq = Server( urlString ) fix_hostname="hostname %s" %hostnames[switch_ip] response = switchReq.runCmds( 1, ["enable","configure",fix_hostname,"end","write"] ) return response
import pyeapi ssl._create_default_https_context = ssl._create_unverified_context username = "******" password = "******" host = "184.105.247.75" list_of_vlans = [] #conn = pyeapi.connect_to("pynet-sw4") #vlans = conn.api("vlans") #all_vlans = vlans.getall() #for key, value in all_vlans.iteritems(): #print key conn = Server("https://%s:%s@%s/command-api" %(username, password, host)) list_cmd = [ "enable", "configure", "show vlan" ] output = conn.runCmds(1, list_cmd, "text") for i in output[2]['output'].split('\n')[2:]: if i != None: list_of_vlans.append(i[0:3]) print ' '.join(list_of_vlans).split()
#!/usr/bin/python """ Created on 10 June 2014 @author: Jere Julian """ from jsonrpclib import Server import pprint #import Foo if __name__ == '__main__': switch = Server("https://*****:*****@10.10.10.11/command-api") response = switch.runCmds(1, ["show interfaces description"]) #print "The switch's system MAC addess is", response[0]["systemMacAddress"] #pp = pprint.PrettyPrinter() #pp.pprint(response[0]) pprint.pprint(response[0]) print "The switch's system Management description is '{0}' and it is {1}/{2}.".format( response[0]["interfaceDescriptions"]["Management1"]["description"], response[0]["interfaceDescriptions"]["Management1"]["interfaceStatus"], response[0]["interfaceDescriptions"]["Management1"]["lineProtocolStatus"])