def _execute(argv,length_of_argv): global dev_ip,credential_file,command,device,inputcsv,cmdFile if length_of_argv > 2: """ Will execute if user input is device(s)""" if dev_ip: div_ip_arr = dev_ip.split(",") if _file_exist_with_valid_type(credential_file,".csv"): with open(credential_file, 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: for ip in div_ip_arr: if ip == row[0]: username = row[1] password = row[2] target_url = "http://"+str(ip)+"/ins" try: NXAPITransport.init(target_url=target_url, username=username, password=password, timeout=50000) except Exception as e: logger.error("Not able to connect to NXAPI: %s",str(e)) raise _execute_command(command=command,device=ip) # Will execute if user input is inputcsv(s) elif inputcsv: inputcsv_arr = inputcsv.split(",") for file in inputcsv_arr: _prepare_and_execute(os.path.join(sys.path[0],file)) else: """ this else block will use default credentials.csv file """ """ Will execute if user input is cmdFile """ """ Will execute if user input is command """ _prepare_and_execute(credential_file)
def _prepare_and_execute(file_name): global command,cmdFile filename = file_name if _file_exist_with_valid_type(filename,".csv"): try: with open(filename, 'rb') as f: reader = csv.reader(f, delimiter='\t') for row in reader: device = row[0] username = row[1] password = row[2] target_url = "https://"+str(device)+"/ins" try: NXAPITransport.init(target_url=target_url, username=username, password=password, timeout=50000) except Exception as e: logger.error("Nexus Error: Not able to connect to NXAPI: %s",str(e)) raise if cmdFile: cmdFile = os.path.join(os.path.dirname(os.path.realpath(__file__)),cmdFile) file = open(cmdFile, 'r') cmdList = file.readlines() for cmdIn in cmdList: cmdIn=cmdIn.strip() (cmdIn,component)=cmdIn.split(',') cmdIn=cmdIn.strip() _execute_command(command=cmdIn,device=device,component=component) elif command: _execute_command(command=command,device=device) except Exception as err: logger.error("Nexus Error: Not able to execute command: %s ",str(err)) raise
def runNXAPIShow(cmd): xml_index = cmd.find("| xml") if xml_index == -1: output, code, msg = NXAPITransport.send_cmd_int(cmd, "cli_show_ascii") else: cmd = cmd[:xml_index] output, code, msg = NXAPITransport.send_cmd_int(cmd, "cli_show") return output
def runNXAPIShow(cmd): xml_index = cmd.find("| xml") if xml_index == -1: output,code,msg = NXAPITransport.send_cmd_int(cmd, "cli_show_ascii") else: cmd = cmd[:xml_index] output,code,msg = NXAPITransport.send_cmd_int(cmd, "cli_show") return output
def smartcli(*args): """This wrapper function provides a less intrusive way to call the appropriate msg_type for configuration based commands """ cmd = args[0] if cmd[:4] == 'conf': NXAPITransport.send_cmd(cmd, msg_type='cli_conf') else: NXAPITransport.cli(cmd)
def mclic (self, switches, command): ''' Runs a command on multiple switches (defined in the class variable multicli.switches). No values are returned ''' output = [] for switch in switches: target_url = "http://" + switch[1] + "/ins" myswitchname = switch[0] self.printdebug ("Running command " + command + " on " + myswitchname) myusername = switch[2] mypassword = switch[3] NXAPITransport.init(target_url=target_url, username=myusername, password=mypassword) try: NXAPITransport.clic (command) except: self.printdebug ("Error sending command " + command + " on " + myswitchname) pass
def _execute_command(command,device,component='N/A'): try: cmd_out= NXAPITransport.clid(command) except Exception as e: logger.error("Nexus Error: Not able to Execute command through NXAPI: %s",str(e)) raise cmd_json=json.loads(cmd_out) if cmd_json != None: dataKeys=cmd_json.keys() rowKeyVal = [] for i in range(len(dataKeys)): if not "TABLE" in dataKeys[i]: check_type = cmd_json[dataKeys[i]] if type(check_type) is unicode: value=cmd_json[dataKeys[i]] key_value = {dataKeys[i]:value} rowKeyVal.append(key_value) if type(check_type) is dict: internal_single_row = cmd_json[dataKeys[i]]#single_row has inside raw data in k:v pair internalDataKeys = internal_single_row.keys() internalTableNames=[] internalRowNames=[] for table in internalDataKeys: if not "TABLE" in table: internal_value = internal_single_row[table] if type(internal_value) is unicode: currentTime= datetime.now().strftime('%Y-%m-%d %H:%M:%S%z') internal_key_value = {table:internal_value} response = {"timestamp":currentTime,"component":component,"device":device,"Row_info":internal_key_value} print json.dumps(response,ensure_ascii=False) logger.info("Successfully executed %s cli on switch %s",command,device) if type(internal_value) is dict: currentTime= datetime.now().strftime('%Y-%m-%d %H:%M:%S%z') response = {"timestamp":currentTime,"component":component,"device":device,"Row_info":internal_single_row[table]} print json.dumps(response,ensure_ascii=False) logger.info("Successfully executed %s cli on switch %s",command,device) if "TABLE" in table: internalTableNames.append(table) row=table.replace("TABLE","ROW") internalRowNames.append(row) for i in range(len(internalTableNames)): _split_json(device,component,internal_single_row,internalTableNames[i],internalRowNames[i]) if rowKeyVal: _display_data(device,component,rowKeyVal) tableNames=[] rowNames=[] for table in dataKeys: if "TABLE" in table: tableNames.append(table) row=table.replace("TABLE","ROW") rowNames.append(row) for i in range(len(tableNames)): _split_json(device,component,cmd_json,tableNames[i],rowNames[i])
def scli (self, myswitchname, command): ''' Runs a command on a single switch, taking the parameters out of the class variable 'switches'. Output as a raw string ''' for switch in self.switches: if switch[0] == myswitchname: target_url = "http://" + switch[1] + "/ins" username = switch[2] password = switch[3] NXAPITransport.init(target_url=target_url, username=username, password=password) try: output = NXAPITransport.cli (command) except: self.printdebug ("Error sending command " + command + " on " + myswitchname) return False return output if not output: print "Switch %s not found!" % myswitchname return False
def mclid (self, switches, command): ''' Runs a command on multiple switches (defined in the class variable multicli.switches) and returns the results in a bidimensional matrix where the first column contains the switch name, and the second the JSON output ''' output = [] for switch in switches: target_url = "http://" + switch[1] + "/ins" myswitchname = switch[0] self.printdebug ("Running command " + command + " on " + myswitchname) myusername = switch[2] mypassword = switch[3] NXAPITransport.init(target_url=target_url, username=myusername, password=mypassword) try: thisoutput = NXAPITransport.clid (command) output.append ( [myswitchname, thisoutput] ) except: self.printdebug ("Error sending command '" + command + "' on " + myswitchname) return output
if isinstance(v, list) or isinstance(v, dict): f = findkey(v, key, value) if f: found.extend(f) if str(k) == str(key): if (value and str(v) == str(value)) or not value: found.append(v) return found if len(found) > 0 else None for switch in switches: cdp_dict = {} if not onbox: target_url = "http://%s/ins" % switch[0] username = switch[1] password = switch[2] NXAPITransport.init( target_url=target_url, username=username, password=password) def smartcli(*args): """This wrapper function provides a less intrusive way to call the appropriate msg_type for configuration based commands """ cmd = args[0] if cmd[:4] == 'conf': NXAPITransport.send_cmd(cmd, msg_type='cli_conf') else: NXAPITransport.cli(cmd) cli = smartcli clid = NXAPITransport.clid cdp_dict = {}
import json sys.path.append("./cisco") sys.path.append("./utils") from nxapi_utils import NXAPITransport from cisco.interface import Interface switches = [ ['172.23.3.116', 'admin', 'insieme'], ['172.23.3.117', 'admin', 'insieme']] results = [] for switch in switches: target_url = "http://%s/ins" % switch[0] username = switch[1] password = switch[2] NXAPITransport.init(target_url=target_url, username=username, password=password) results.append(json.loads(NXAPITransport.clid("show version"))) switchlist = [r['host_name'] for r in results] fmt = "{:>45}" * (len(switchlist) + 1) print fmt.format("", *switchlist) for k,v in results[0].items(): values = [] for i,r in enumerate(results[1:]): values.append(v) mismatch = False if k in r: values.append(r[k]) if r[k] != v: mismatch = True
import sys sys.path.append("./cisco") sys.path.append("./utils") from nxapi_utils import NXAPITransport from cisco.interface import Interface ################### # NXAPI init block ################### target_url = "http://10.30.14.8/ins" username = "******" password = "******" NXAPITransport.init(target_url=target_url, username=username, password=password) ################### ################### # cli/clip/clid are changed a bit, but largely the same ################### print NXAPITransport.cli("show version") NXAPITransport.clip("show interface brief") NXAPITransport.clic("conf t ;interface eth4/1 ;no shut") print NXAPITransport.clid("show version") ###################
def runNXAPIConf(cmd): output, code, msg = NXAPITransport.send_cmd_int(cmd, "cli_conf") return output, msg, code
# All rights reserved import sys sys.path.append("./cisco") sys.path.append("./utils") from nxapi_utils import NXAPITransport from cisco.interface import Interface ################### # NXAPI init block ################### target_url = "http://10.30.14.8/ins" username = "******" password = "******" NXAPITransport.init(target_url=target_url, username=username, password=password) ################### ################### # cli/clip/clid are changed a bit, but largely the same ################### print NXAPITransport.cli("show version") NXAPITransport.clip("show interface brief") NXAPITransport.clic("conf t ;interface eth4/1 ;no shut") print NXAPITransport.clid("show version") ################### # Below is exactly the same as the usage on the switch. Do whatever you
#!/usr/bin/env python## Copyright (C) 2014 Cisco Systems Inc.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.## This script demonstrates how you can write a single script that runs on both# on box and off box, using the same APIs on Nexus 9000.## The workflow will gather details from the CDP database and generate# interface descriptions based on the neighbor name and remote interface# and then print out the configuration needed to apply these descriptions.# This version executes via the NX-API, and will simply print out the# generated configuration output, as opposed to applying it# # Define your list of switches here, with their IP addresses and credentialsswitches = [ ['172.31.216.131', 'admin', 'cisco123'], ['172.31.216.131', 'admin', 'cisco123']] import sysimport pprintimport jsonsys.path.append("./cisco")sys.path.append("./utils") onbox = Falsetry: from cli import clid, cliexcept ImportError: try: from nxapi_utils import NXAPITransport from cisco.interface import Interface onbox = False except ImportError: print 'Script is unsupported on this platform' raise from nxapi_utils import NXAPITransportfrom cisco.interface import Interfacedef findkey(dct, key, value=None): """This method recursively searches through a JSON dict for a key name and returns a list of the matching results """ found = [] if isinstance(dct, list): for item in dct: f = findkey(item, key, value) if f: found.extend(f) if isinstance(dct, dict): for k, v in dct.items(): if isinstance(v, list) or isinstance(v, dict): f = findkey(v, key, value) if f: found.extend(f) if str(k) == str(key): if (value and str(v) == str(value)) or not value: found.append(v) return found if len(found) > 0 else None for switch in switches: cdp_dict = {} if not onbox: target_url = "http://%s/ins" % switch[0] username = switch[1] password = switch[2] NXAPITransport.init( target_url=target_url, username=username, password=password) def smartcli(*args): """This wrapper function provides a less intrusive way to call the appropriate msg_type for configuration based commands """ cmd = args[0] if cmd[:4] == 'conf': NXAPITransport.send_cmd(cmd, msg_type='cli_conf') else: NXAPITransport.cli(cmd) cli = smartcli clid = NXAPITransport.clid cdp_dict = {} cdp = json.loads(clid('show cdp neighbor')) cdp = findkey(cdp, 'ROW_cdp_neighbor_brief_info')[0] for entry in cdp: intf_id = entry['intf_id'] if intf_id not in cdp_dict: cdp_dict[intf_id] = { 'intf_id': intf_id, 'device_id': entry['device_id'], 'port_id': entry['port_id'] } for key, value in cdp_dict.items(): if 'port_id' in value and 'device_id' in value and 'intf_id' in value: fields = { 'interface': value['intf_id'].strip().encode('UTF-8'), 'device_id': value['device_id'].strip().encode('UTF-8'), 'port_id': value['port_id'].strip().encode('UTF-8') } cmd = 'conf t ; interface {interface} ; description {device_id} {port_id}'.format( **fields) print(cmd) cli(cmd)
if f: found.extend(f) if str(k) == str(key): if (value and str(v) == str(value)) or not value: found.append(v) return found if len(found) > 0 else None for switch in switches: cdp_dict = {} if not onbox: target_url = "http://%s/ins" % switch[0] username = switch[1] password = switch[2] NXAPITransport.init(target_url=target_url, username=username, password=password) def smartcli(*args): """This wrapper function provides a less intrusive way to call the appropriate msg_type for configuration based commands """ cmd = args[0] if cmd[:4] == 'conf': NXAPITransport.send_cmd(cmd, msg_type='cli_conf') else: NXAPITransport.cli(cmd) cli = smartcli clid = NXAPITransport.clid
sys.path.append("./cisco") sys.path.append("./utils") from nxapi_utils import NXAPITransport from cisco.interface import Interface switches = [['172.23.3.116', 'admin', 'insieme'], ['172.23.3.117', 'admin', 'insieme']] results = [] for switch in switches: target_url = "http://%s/ins" % switch[0] username = switch[1] password = switch[2] NXAPITransport.init(target_url=target_url, username=username, password=password) results.append(json.loads(NXAPITransport.clid("show version"))) switchlist = [r['host_name'] for r in results] fmt = "{:>45}" * (len(switchlist) + 1) print fmt.format("", *switchlist) for k, v in results[0].items(): values = [] for i, r in enumerate(results[1:]): values.append(v) mismatch = False if k in r: values.append(r[k])
import json sys.path.append("./cisco") sys.path.append("./utils") from nxapi_utils import NXAPITransport from cisco.interface import Interface switches = [ ['172.23.3.116', 'admin', 'insieme'], ['172.23.3.117', 'admin', 'insieme']] for switch in switches: cdp_dict = {} target_url = "http://%s/ins" % switch[0] username = switch[1] password = switch[2] NXAPITransport.init(target_url=target_url, username=username, password=password) cdp = json.loads(NXAPITransport.clid('show cdp neighbor'))['TABLE_cdp_neighbor_brief_info']['ROW_cdp_neighbor_brief_info'] for entry in cdp: intf_id = entry['intf_id'] if intf_id not in cdp_dict: cdp_dict[intf_id] = {} cdp_dict[intf_id]['intf_id'] = entry['intf_id'] cdp_dict[intf_id]['device_id'] = entry['device_id'] cdp_dict[intf_id]['port_id'] = entry['port_id'] print 'configuration for switch %s' % switch[0] for key,value in cdp_dict.items(): if 'port_id' in value and 'device_id' in value and 'intf_id' in value: print 'interface ' + value['intf_id']
def runNXAPIConf(cmd): output,code,msg = NXAPITransport.send_cmd_int(cmd, "cli_conf") return output,msg,code