Пример #1
0
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]) 
Пример #2
0
 def sclid (self, myswitchname, command):
     '''
     Runs a command on a single switch, taking the parameters out of the
     class variable 'switches'. Output as JSON
     '''
     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.clid (command)
         except:
             self.printdebug ("Error sending command " + command + " on " + myswitchname)
             return False
         return output
     if not output:
       print "Switch %s not found!" % switchName
       return False
Пример #3
0
 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
Пример #4
0
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
		if mismatch is True: print fmt.format(k, *values)
Пример #5
0
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
# are already doing on the switch right now!
###################
print Interface.interfaces()

i = Interface("Ethernet4/1")

print i.show(key="eth_mtu")

i.set_description(d="ifx4/1")
Пример #6
0
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
# are already doing on the switch right now!
###################
print Interface.interfaces()

i = Interface("Ethernet4/1")

print i.show(key="eth_mtu")

i.set_description(d="ifx4/1")


Пример #7
0
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
        if mismatch is True: print fmt.format(k, *values)
Пример #8
0
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']
            print '  description ' + value['device_id'] + ' ' + value['port_id']