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 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 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 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") ###################
#!/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)