コード例 #1
0
 def __init__(self, ip, port):
     self.switch = FlexSwitch(ip, port)
コード例 #2
0
ファイル: snap_commands.py プロジェクト: ashutoshshanker/apps
class FlexSwitch_info():

   def __init__(self,switch_ip):
   		self.switch_ip=switch_ip
   		self.swtch = FlexSwitch(self.switch_ip,8080)


   def displayRunBGP(self):
     	neigh = self.swtch.getObjects('BGPNeighborStates')
     	#globalc = self.swtch.getObjects('BGPGlobals')
     	#peers = self.swtch.getObjects('BGPPeerGroups')
		
     	#if len(globalc)>=0:
     	#    print globalc   
     	    
     	if len(neigh)>=0:
     	    print neigh 
     	    
     	#if len(peers)>=0:
     	#    print peers 

   		
   def displayBGPPeers(self):	   
		   sessionState=  {  0: "Idle",
							 1: "Connect",
							 2: "Active",
							 3: "OpenSent",
							 4: "OpenConfirm",
							 5: "Established"
						   } 
	
		   peers = self.swtch.getObjects('BGPNeighborStates')
		   if len(peers)>=0: 
			   print '\n'
			   print 'Neighbor   LocalAS   PeerAS     State      RxNotifications    RxUpdates   TxNotifications TxUpdates  Description'
		   for pr in peers:
			   print '%s %s %s     %s       %s              %s              %s           %s	%s' %(pr['Object']['NeighborAddress'].ljust(12),
																				  str(pr['Object']['LocalAS']).ljust(8),
																				  pr['Object']['PeerAS'],
																				  sessionState[int(pr['Object']['SessionState'] -1)],
																				  pr['Object']['Messages']['Received']['Notification'],
																				  pr['Object']['Messages']['Received']['Update'],
																				  pr['Object']['Messages']['Sent']['Notification'],
																				  pr['Object']['Messages']['Sent']['Update'],
																				  pr['Object']['Description'])

		   print "\n" 
		   
   def displayBGPtable(self):
     	routes = self.swtch.getObjects('BGPRoutes')
     	if len(routes)>=0:
     	    print '\n'
     	    print 'Network          Mask           NextHop          Metric     LocalPref      Updated   		Path'
     	for rt in routes:
     	    print '%s %s %s %4d   %9d    %14s   %13s' %(rt['Object']['Network'].ljust(17), 
     	                                                    str(rt['Object']['CIDRLen']).ljust(13),
     	                                                    rt['Object']['NextHop'].ljust(15), 
     	                                                    rt['Object']['Metric'], 
     	                                                    rt['Object']['LocalPref'], 
     	                                                    rt['Object']['UpdatedDuration'].split(".")[0],
     	                                                    rt['Object']['Path'])
        print "\n"

   def displayBfdNeigh(self):
     	neigh = self.swtch.getObjects('BfdSessionStates')
     	if len(neigh)>=0:
     		print "BFD Neighbors"
     		print "********************************************************************************************"    	    
     	for rt in neigh:
     	    print 'Session ID:', rt['Object']['SessionId']
     	    print 'Interface:'
     	    print 'IfIndex:',rt['Object']['IfIndex']     	    
     	    print 'LocalIP:', rt['Object']['LocalIpAddr']       
     	    print 'Remote IP:' ,rt['Object']['IpAddr'] 
     	    print 'Local State:',rt['Object']['SessionState'] 
     	    print 'Remote State:', rt['Object']['RemoteSessionState'] 
     	    print 'Local Descrim:', rt['Object']['LocalDiscriminator'] 
     	    print 'Remote Descrim:', rt['Object']['RemoteDiscriminator']
     	    print 'TxPackets:',rt['Object']['NumTxPackets']
     	    print 'RxPackets:',rt['Object']['NumRxPackets']
     	    print 'Multiplier:',rt['Object']['DetectionMultiplier']
     	    print 'MinTxInt:',rt['Object']['DesiredMinTxInterval'] 
     	    print 'MinRxInt:',rt['Object']['RequiredMinRxInterval'] 	   	 
     	    print 'LocalDiag:',rt['Object']['LocalDiagType'] 
     	    print 'RegisteredProtocols:',  rt['Object']['RegisteredProtocols']
     	    print "********************************************************************************************"
     	    
     	print "\n"        

   def displayBfdInt(self):
   		int = self.swtch.getObjects('BfdInterfaceStates')
   		if len(int)>=0:
   			print 'BFD Interfaces'
   			print "********************************************************************************************"
   		for rt in int:
   			print 'Interface:', 
   			print 'IfIndex:',rt['Object']['IfIndex'] 
   			print 'Enabled:',rt['Object']['Enabled']
   			print 'NumSessions:',rt['Object']['NumSessions']
   			print 'Multiplier:',rt['Object']['LocalMultiplier']
   			print 'MinTxInt:',rt['Object']['DesiredMinTxInterval'] 
   			print 'MinRxInt:',rt['Object']['RequiredMinRxInterval']
   			print "********************************************************************************************"
   		
		print "\n"   			
	   
   def displayRoutes(self):
     	routes = self.swtch.getObjects('IPv4RouteStates')
     	if len(routes)>=0:
     	    print '\n'
     	    print 'Network         NextHop         Protocol         IfType         IfIndex'
     	for rt in routes:
     	    print '%s %s %s   %s    %s ' %(rt['Object']['DestinationNw'].ljust(15), 
     	                                                    rt['Object']['NextHopIp'].ljust(15), 
     	                                                    rt['Object']['Protocol'].ljust(15), 
     	                                                    rt['Object']['OutgoingIntfType'].ljust(15), 
     	                                                    rt['Object']['OutgoingInterface'].ljust(15))
        print "\n"


   def displayARPEntries(self):
        arps = self.swtch.getObjects('ArpEntryStates')
        if len(arps)>=0:
            print '\n'
            print 'IP Address	MacAddress   	    TimeRemaining  	Vlan 	  Intf'
        for d in arps:
            print  '%s	%s    %s	 %s	%s' %(d['Object']['IpAddr'],
						d['Object']['MacAddr'],
						d['Object']['ExpiryTimeLeft'],
						d['Object']['Vlan'],
						d['Object']['Intf'])
        print "\n"

   def IPv4Intfstatus(self):
     	ip_int = self.swtch.getObjects('IPv4IntfStates')
     	if len(ip_int)>=0:
     	    print '\n'
     	    print 'Interface     IfIndex        IPv4'
     	for d in ip_int:
     		if len(str(d['Object']['IfIndex'])) < 8:
     			if d['Object']['IfIndex'] < 73:
     				index = self.swtch.getObjects('PortStates')
     				for e in index:
     					if e['Object']['IfIndex'] == d['Object']['IfIndex']:
     						port=e['Object']['Name']
     						break
     					else:
     						port='N/A'
     			else:
     				index = self.swtch.getObjects('Vlans')
     				for e in index:
     					if e['Object']['IfIndex'] == d['Object']['IfIndex']:
     						port=e['Object']['VlanName']
     						break
     					else:
     						port='N/A'
     							
     			print '%s %6s %21s' %(port.ljust(10), 
     						d['Object']['IfIndex'],
     					    d['Object']['IpAddr']
     		               )
     		elif len(str(d['Object']['IfIndex'])) >= 8:
     			if d['Object']['IfIndex'] < 73:
     				index = self.swtch.getObjects('PortStates')
     				for e in index:
     					if e['Object']['IfIndex'] == d['Object']['IfIndex']:
     						port=e['Object']['Name']
     						break
     					else:
     						port='N/A'
     			else:
     				index = self.swtch.getObjects('VlanStates')
     				for e in index:
     					if e['Object']['IfIndex'] == d['Object']['IfIndex']:
     						port=e['Object']['VlanName']
     						break
     					else:
     						port='N/A'
     							
     			print '%s %s %13s' %(port.ljust(10), 
     						d['Object']['IfIndex'],
     					    d['Object']['IpAddr']
     		               )     			
     		     	       
        print "\n"  
        
   def displayPortObjects(self):
        ports = self.swtch.getObjects('PortStates')
        if len(ports):
            print '\n'
            print 'Port         InOctets   InUcastPkts   InDiscards  InErrors     InUnknownProtos   OutOctets OutUcastPkts   OutDiscards   OutErrors'
        for d in ports:
            if d['Object']['IfIndex'] == 0:
        		continue
            elif d['Object']['IfIndex'] < 10:
            	print '%s  %8d %10d   %10d    %8d   %15d   %9d   %12d   %11d   %11d' %("fpPort-"+str(d['Object']['IfIndex']),
                                                                d['Object']['IfInOctets'],
                                                                d['Object']['IfInUcastPkts'],
                                                                d['Object']['IfInDiscards'],
                                                                d['Object']['IfInErrors'],
                                                                d['Object']['IfInUnknownProtos'],
                                                                d['Object']['IfOutOctets'],
                                                                d['Object']['IfOutUcastPkts'],
                                                                d['Object']['IfOutDiscards'],
                                                                d['Object']['IfOutErrors'])
            else:
            	print '%s  %7d %10d   %10d    %8d   %15d   %9d   %12d   %11d   %11d' %("fpPort-"+str(d['Object']['IfIndex']),
                                                                d['Object']['IfInOctets'],
                                                                d['Object']['IfInUcastPkts'],
                                                                d['Object']['IfInDiscards'],
                                                                d['Object']['IfInErrors'],
                                                                d['Object']['IfInUnknownProtos'],
                                                                d['Object']['IfOutOctets'],
                                                                d['Object']['IfOutUcastPkts'],
                                                                d['Object']['IfOutDiscards'],
                                                                d['Object']['IfOutErrors'])
        print "\n"
   def displayCPUPortObjects(self):
        ports = self.swtch.getObjects('PortStates')
        if len(ports):
            print '\n'
            print 'Port         InOctets   InUcastPkts   InDiscards  InErrors     InUnknownProtos   OutOctets OutUcastPkts   OutDiscards   OutErrors'
        for d in ports:
            if d['Object']['IfIndex'] == 0:
            	print '%s  %8d %10d   %10d    %8d   %15d   %9d   %12d   %11d   %11d' %("CPU",
                                                                d['Object']['IfInOctets'],
                                                                d['Object']['IfInUcastPkts'],
                                                                d['Object']['IfInDiscards'],
                                                                d['Object']['IfInErrors'],
                                                                d['Object']['IfInUnknownProtos'],
                                                                d['Object']['IfOutOctets'],
                                                                d['Object']['IfOutUcastPkts'],
                                                                d['Object']['IfOutDiscards'],
                                                                d['Object']['IfOutErrors'])

   def displayPortStatus(self):
        ports = self.swtch.getObjects('PortStates')
        if len(ports):
            print '\n'
            print 'Port         Status   IFIndex   Duplex   Speed     Type'
        for d in ports: 
            if d['Object']['IfIndex'] == 0:
        		continue
            elif d['Object']['IfIndex'] < 10:
            	print '%s  %8s %6s %10s %8s %9s' %("fpPort-"+str(d['Object']['IfIndex']),
                                                            d['Object']['OperState'],
                                                             d['Object']['IfIndex'],
                                                             'N/A',
                                                             'N/A',
                                                             'N/A')
            else:
            	print '%s  %7s %6s %10s %8s %9s' %("fpPort-"+str(d['Object']['IfIndex']),
                                                            d['Object']['OperState'],
                                                             d['Object']['IfIndex'],
                                                             'N/A',
                                                             'N/A',
                                                             'N/A')
   def displayVlanInfo(self, vlanId=0):
   		if vlanId == 0:
   			vlans = self.swtch.getObjects('Vlans')
   			if len(vlans):
   				print 'Vlan    Ports 	Untagged_Ports'
   			for d in vlans:
   				print '%s  %8s %8s ' %(str(d['Object']['VlanId']),
   									  d['Object']['IfIndexList'],
   									  d['Object']['UntagIfIndexList'])   			
   		else:
   			vlans = self.swtch.getObjects('Vlans')
   			if len(vlans):
   				print 'Vlan    Ports 	Untagged_Ports'   		
   			found =0
   		   	for d in vlans:
   				if d['Object']['VlanId'] == int(vlanId):
   					found=1
   					print '%s  %8s %8s ' %(str(d['Object']['VlanId']),
   									  	d['Object']['IfIndexList'],
   									  	d['Object']['UntagIfIndexList'])   
   			if found == 0:
   				print "**Vlan doesn't Exist**"						  	

   def verifyDRElectionResult(self):
        ospfIntfs = self.swtch.getObjects('OspfIfEntryStates')
        print '\n'
        #self.assertNotEqual(len(ospfIntfs) != 0)
        if len(ospfIntfs)>=0:
            print 'IfAddr IfIndex  State  DR-RouterId DR-IpAddr BDR-RouterI BDR-IpAddr NumEvents LSACount LSACksum'

        for d in ospfIntfs:
            #if sum(d['ospfIntfs']):
                print '%3s  %3d %10s   %10s    %8s   %15s   %9s   %12s   %11s   %11s' %( d['Object']['IfIpAddressKey'],
                                                                                        d['Object']['AddressLessIfKey'],
                                                                                        d['Object']['IfState'],
                                                                                        d['Object']['IfDesignatedRouter'],
                                                                                        d['Object']['IfBackupDesignatedRouter'],
                                                                                        d['Object']['IfEvents'],
                                                                                        d['Object']['IfLsaCount'],
                                                                                        d['Object']['IfLsaCksumSum'],
                                                                                        d['Object']['IfDesignatedRouterId'],
                                                                                        d['Object']['IfBackupDesignatedRouterId'])
        print "\n"            

   def getLagMembers(self):
      members = self.swtch.getObjects('AggregationLacpMemberStateCounterss')
      print '\n---- LACP Members----'
      if len(members):
   	   for d in members:
   		   print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n'
   		   print 'name: ' + d['Object']['NameKey'] + ' interface: ' + d['Object']['Interface']
   		   print 'enabled: %s' % d['Object']['Enabled']
   		   print 'lagtype: ' + ('LACP' if not d['LagType'] else 'STATIC')
   		   print 'operkey: %s' % d['Object']['OperKey']
   		   print 'mode: ' + ('ACTIVE' if not d['Object']['LacpMode'] else 'PASSIVE')
   		   print 'interval: %s' % (('SLOW' if d['Object']['Interval'] else 'FAST'))
   		   print 'system:\n'
   		   print '\tsystemmac: %s' % d['Object']['SystemIdMac']
   		   print '\tsysteprio: %s' % d['Object']['SystemPriority']
   		   print '\tsystemId: %s' % d['Object']['SystemId']
   		   print 'actor:'
   		   stateStr = '\tstate: '
   		   for s in ('Activity', 'Timeout', 'Aggregatable', 'Synchronization', 'Collecting', 'Distributing'):
   			   if s == 'Synchronization' and not d['Object'][s]:
   				   stateStr += s + ', '
   			   elif s == 'Activity' and not d['Object'][s]:
   				   stateStr += s + ', '
   			   elif s in ('Activity', 'Synchronization'):
   				   continue
   			   elif d[s]:
   				   stateStr += s + ', '
   		   print stateStr.rstrip(',')
   
   		   print '\tstats:'
   		   for s in ('LacpInPkts', 'LacpOutPkts', 'LacpRxErrors', 'LacpTxErrors', 'LacpUnknownErrors', 'LacpErrors', 'LampInPdu', 'LampOutPdu', 'LampInResponsePdu', 'LampOutResponsePdu'):
   			   print '\t' + s, ': ', d['Object'][s]
   
   		   print 'partner:\n'
   		   print '\t' + 'key: %s' % d['Object']['PartnerKey']
   		   print '\t' + 'partnerid: ' + d['Object']['PartnerId']
   


   def getLagMembers_detail(self): 
      RxMachineStateDict = {
          0 : "RX_CURRENT",
          1 : "RX_EXPIRED",
          2 : "RX_DEFAULTED",
          3 : "RX_INITIALIZE",
          4 : "RX_LACP_DISABLED",
      	5 : "RX_PORT_DISABLE",
      }
      
      MuxMachineStateDict = {
          0 : "MUX_DETACHED",
          1 : "MUX_WAITING",
          2 : "MUX_ATTACHED",
          3 : "MUX_COLLECTING",
      	4 : "MUX_DISTRIBUTING",
          5 : "MUX_COLLECTING_DISTRIBUTING",
      }
      
      ChurnMachineStateDict = {
          0 : "CDM_NO_CHURN",
          1 : "CDM_CHURN",
      }
      members = self.swtch.getObjects('AggregationLacpMemberStateCounterss')
      print '\n---- LACP Members----'
      if len(members):
   	   for d in members:
   		   print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n'
   		   print 'name: ' + d['Object']['NameKey'] + ' interface: ' + d['Interface']
   		   print 'enabled: %s' % d['Object']['Enabled']
   		   print 'lagtype: ' + ('LACP' if not d['Object']['LagType'] else 'STATIC')
   		   print 'operkey: %s' % d['Object']['OperKey']
   		   print 'mode: ' + ('ACTIVE' if not d['Object']['LacpMode'] else 'PASSIVE')
   		   print 'interval: %s' % (('SLOW' if d['Object']['Interval'] else 'FAST'))
   		   print 'system:\n'
   		   print '\tsystemmac: %s' % d['Object']['SystemIdMac']
   		   print '\tsysteprio: %s' % d['Object']['SystemPriority']
   		   print '\tsystemId: %s' % d['Object']['SystemId']
   		   print 'actor:'
   		   stateStr = '\tstate: '
   		   for s in ('Activity', 'Timeout', 'Aggregatable', 'Synchronization', 'Collecting', 'Distributing'):
   			   if s == 'Synchronization' and not d['Object'][s]:
   				   stateStr += s + ', '
   			   elif s == 'Activity' and not d['Object'][s]:
   				   stateStr += s + ', '
   			   elif s in ('Activity', 'Synchronization'):
   				   continue
   			   elif d[s]:
   				   stateStr += s + ', '
   		   print stateStr.rstrip(',')
   
   		   print '\tstats:'
   		   for s in ('LacpInPkts', 'LacpOutPkts', 'LacpRxErrors', 'LacpTxErrors', 'LacpUnknownErrors', 'LacpErrors', 'LampInPdu', 'LampOutPdu', 'LampInResponsePdu', 'LampOutResponsePdu'):
   			   print '\t' + s, ': ', d['Object'][s]
   
   		   print 'partner:\n'
   		   print '\t' + 'key: %s' % d['Object']['PartnerKey']
   		   print '\t' + 'partnerid: ' + d['Object']['PartnerId']
   		   print 'debug:\n'
   		   try:
   			   print '\t' + 'debugId: %s' % d['Object']['DebugId']
   			   print '\t' + 'RxMachineState: %s' % RxMachineStateDict[d['Object']['RxMachine']]
   			   print '\t' + 'RxTime (rx pkt rcv): %s' % d['Object']['RxTime']
   			   print '\t' + 'MuxMachineState: %s' % MuxMachineStateDict[d['Object']['MuxMachine']]
   			   print '\t' + 'MuxReason: %s' % d['Object']['MuxReason']
   			   print '\t' + 'Actor Churn State: %s' % ChurnMachineStateDict[d['Object']['ActorChurnMachine']]
   			   print '\t' + 'Partner Churn State: %s' % ChurnMachineStateDict[d['Object']['PartnerChurnMachine']]
   			   print '\t' + 'Actor Churn Count: %s' % d['Object']['ActorChurnCount']
   			   print '\t' + 'Partner Churn Count: %s' % d['Object']['PartnerChurnCount']
   			   print '\t' + 'Actor Sync Transition Count: %s' % d['Object']['ActorSyncTransitionCount']
   			   print '\t' + 'Partner Sync Transition Count: %s' % d['Object']['PartnerSyncTransitionCount']
   			   print '\t' + 'Actor LAG ID change Count: %s' % d['Object']['ActorChangeCount']
   			   print '\t' + 'Partner LAG ID change Count: %s' % d['Object']['PartnerChangeCount']
   		   except Exception as e:
   			   print e      
   
   def getLagGroups(self):
      lagGroup = self.swtch.getObjects('AggregationLacpStates')
      print '\n'
      if len(lagGroup)>=0:
   	   print 'Name      Ifindex      LagType   Description      Enabled   MinLinks   Interval   Mode          SystemIdMac            SystemPriority    HASH'
   
   	   for d in lagGroup:
   		   print '%7s  %7s    %7s  %15s    %8s   %2s     %8s      %6s   %20s         %s              %s' %(d['Object']['NameKey'],
   														   d['Object']['Ifindex'],
   														   "LACP" if int(d['Object']['LagType']) == 0 else "STATIC",
   														   d['Description'],
   														   "Enabled" if bool(d['Object']['Enabled']) else "Disabled",
   														   d['Object']['MinLinks'],
   														   "FAST" if int(d['Object']['Interval']) == 0 else "SLOW",
   														   "ACTIVE" if int(d['Object']['LacpMode']) == 0 else "PASSIVE",
   														   d['Object']['SystemIdMac'],
   														   d['Object']['SystemPriority'],
   														   d['Object']['LagHash'])
コード例 #3
0
 def get_bfdstats(self, stwitch_ip):
     swtch = FlexSwitch(stwitch_ip,
                        8080)  # Instantiate object to talk to flexSwitch
     bfds = swtch.getAllBfdSessionStates()
     return bfds
コード例 #4
0
class FlexSwitchShow(object):
    httpSuccessCodes = [200, 201, 202, 204]

    def __init__(self, ip, port):
        self.switch = FlexSwitch(ip, port)

    def table_print_object(self, obj_name, header, values_list):
        """
        Prints the data in a table format
        obj_name - Object which is being printed
        keys - This will be the attributes of the obj and column names
        valueList - List of tuples containing the data to be put into
                    the rows_list.  Each attribute must be in string format
        """
        def terminal_size():
            import fcntl, termios, struct
            h, w, hp, wp = struct.unpack(
                'HHHH',
                fcntl.ioctl(0, termios.TIOCGWINSZ,
                            struct.pack('HHHH', 0, 0, 0, 0)))
            return h, w

        labels_value = header
        rows_list = values_list

        height, width_value = terminal_size()
        if labels_value:
            width_value = (width_value / len(labels_value)) + 5
            var1 = indent(
                [labels_value] + rows_list,
                has_header=True,
                separate_rows=True,
                prefix=' ',
                postfix=' ',
                header_char='-',
                delimit='    ',
                wrapfunc=lambda x: wrap_onspace_strict(x, width_value))

            return var1
        elif rows_list:
            width_value = (width_value / len(rows_list[0])) + 5
            var1 = indent(
                rows_list,
                has_header=False,
                separate_rows=True,
                prefix=' ',
                postfix=' ',
                header_char='-',
                delimit='    ',
                wrapfunc=lambda x: wrap_onspace_strict(x, width_value))
            return var1
        else:
            print('No Data To Display for %s' % obj_name)
            return 0

    def print_lldp_intf_states(self, add_header=True, brief=None):
        header = []
        rows_list = []
        if add_header:
            header.append('IntfRef')
            header.append('IfIndex')
            header.append('SendFrames')
            header.append('ReceivedFrames')
            header.append('Enable')
            header.append('LocalPort')
            header.append('PeerMac')
            header.append('PeerPort')
            header.append('PeerHostName')
            header.append('HoldTime')
            header.append('SystemDescription')
            header.append('SystemCapabilities')
            header.append('EnabledCapabilities')

        objs = self.switch.get_all_lldp_intf_states()
        for obj in objs:
            o = obj['Object']
            values_list = []
            values_list.append('%s' % o['IntfRef'])
            values_list.append('%s' % o['IfIndex'])
            values_list.append('%s' % o['SendFrames'])
            values_list.append('%s' % o['ReceivedFrames'])
            values_list.append('%s' % o['Enable'])
            values_list.append('%s' % o['LocalPort'])
            values_list.append('%s' % o['PeerMac'])
            values_list.append('%s' % o['PeerPort'])
            values_list.append('%s' % o['PeerHostName'])
            values_list.append('%s' % o['HoldTime'])
            values_list.append('%s' % o['SystemDescription'])
            values_list.append('%s' % o['SystemCapabilities'])
            values_list.append('%s' % o['EnabledCapabilities'])
            rows_list.append(values_list)
        var1 = self.table_print_object('LLDPIntfState', header, rows_list)
        return var1

    def print_combined_vlan_states(self, add_header=True, brief=None):
        header = []
        rows_list = []
        if add_header:
            header.append('VlanId')
            header.append('VlanName')
            header.append('OperState')
            header.append('IfIndex')
            #header.append('SysInternalDescription')
            header.append('IntfList')
            header.append('UntagIntfList')
            #header.append('AdminState')

        objs = self.switch.get_all_vlan_states()
        for obj in objs:
            o = obj['Object']
            values_list = []
            values_list.append('%s' % o['VlanId'])
            values_list.append('%s' % o['VlanName'])
            values_list.append('%s' % o['OperState'])
            values_list.append('%s' % o['IfIndex'])
            #values_list.append('%s' % o['SysInternalDescription'])
            r = self.switch.get_vlan(o['VlanId'])
            if r.status_code in self.httpSuccessCodes:
                o = r.json()['Object']
                values_list.append('%s' % o['IntfList'])
                values_list.append('%s' % o['UntagIntfList'])
                #values_list.append('%s' % o['AdminState'])
            rows_list.append(values_list)
        var = self.table_print_object('VlanState', header, rows_list)
        return var
コード例 #5
0
 def get_portconfigs(self, switch_ip):
     swtch = FlexSwitch(switch_ip, 8080)
     portscfg = swtch.getAllPorts()
     return portscfg
コード例 #6
0
    def get_nhstats(self, stwitch_ip):
        swtch = FlexSwitch (stwitch_ip, 8080)  # Instantiate object to talk to flexSwitch
	nhs = swtch.getAllIPv4RouteStates()
        return nhs
コード例 #7
0
import sys
import os

sys.path.append(os.path.abspath('../../py'))
from flexswitchV2 import FlexSwitch
"""This program demonstrates 
   simple update APIs supported by FlexSwitch SDK. 
   This specific example modifies speed of a port
   All the update APIs follow similar pattern.
   for object 'OBJ_X" the update API would be
   updateOBJ_X (key, parameter= value)
   """

if __name__ == '__main__':
    swtch = FlexSwitch('10.1.10.240',
                       8080)  # Instantiate object to talk to flexSwitch
    response, error = swtch.updatePort(1, Speed=1000)
    if error != None:  #Error not being None implies there is some problem
        print error
    else:
        print 'Updated port speed successfully'
コード例 #8
0
    def get_bufferstats(self, stwitch_ip):
        swtch = FlexSwitch (stwitch_ip, 8080)  # Instantiate object to talk to flexSwitch
	buffers = swtch.getAllBufferPortStatStates()
        return buffers
コード例 #9
0
ファイル: flexprint.py プロジェクト: ashutoshshanker/flexSdk
class FlexPrint( object):
    def  __init__ (self, ip, port):
        self.swtch = FlexSwitch(ip, port)

    def printPortState(self, IntfRef):

        self.printPortStates(IntfRef=int(IntfRef))

    def printPortStates(self, IntfRef=None):

        ports = self.swtch.getAllPortStates()
        for port in ports:
        	p = port['Object']

        	if IntfRef == None or IntfRef == p['IntfRef']:
        		port_config = self.swtch.getPort(p['IntfRef']).json()
        		pc = port_config['Object'] 
        		ipv4_state = self.swtch.getIPv4IntfState(p['IntfRef']).json()
        		#print ipv4_state
        		if ipv4_state.has_key('Error'):
        			ipv4 = None
        		else:
        			ipv4 = ipv4_state['Object']
        		if not p['LastDownEventTime']:
        			lastdown="never"
        		else:
        			lastdown = p['LastDownEventTime']
        		if not p['LastUpEventTime']:
        			lastdown="never"
        		else:
        			lastdown = p['LastDownEventTime']
        		
        		print p['Name'], "is", p['OperState'], "Admin State is", pc['AdminState'] 
        		if ipv4 is not None:
        			print "  IPv4 Address is", ipv4['IpAddr']
        		print "  PresentInHW:", p['PresentInHW']
        		print "  PhyType:", pc['PhyIntfType'],",","Media Type:",pc['MediaType'],"," , "Address:", pc['MacAddr']
        		print "  MTU",  pc['Mtu'],"Bytes"
        		print " ",pc['Duplex'],",",pc['Speed'],"Mb/s"
        		print "  Breakout Status:", pc['BreakOutMode']
        		print "  Last link down:",p['LastDownEventTime']
        		print "  Last link up:",   p['LastUpEventTime']
        		print "  Number of Link flaps:", p['NumDownEvents']
        		print "  ErrDisableReason:", p['ErrDisableReason']
        		print "  RX"
        		print "   ",p['IfInUcastPkts'],"unicast packets",p['IfInOctets'],"unicast octets"
        		print "   ",p['IfInDiscards'],"input discards", p['IfInErrors'], "input errors"
        		print "   ",p['IfInUnknownProtos'],"unknown protocol"
        		print "  TX"
        		print "   ",p['IfOutUcastPkts'],"unicast packets",p['IfOutOctets'],"unicast octets"
        		print "   ",p['IfOutDiscards'],"output discards", p['IfOutErrors'], "output errors"					
        		print '------------------------------------------------------------------------------'
        		
    def printIPv4RouteStates(self):
        routes = self.swtch.getAllIPv4RouteStates()     
        print "IP Route Table"
        print "'[x/y]' denotes [preference/metric]"
        print "\n"    	
        for r in routes:
            rt = r['Object']
            rt_spec = self.swtch.getIPv4RouteState(rt['DestinationNw']).json()
            rt_next=rt_spec['Object']
            rt_count = len(rt_next['NextHopList'])  
            route_distance = self.swtch.getRouteDistanceState(rt['Protocol']).json()
            rd = route_distance['Object']    
            if rt['PolicyList'] is None:
            	policy=rt['PolicyList']
            else:
                policy = str(rt['PolicyList']).split("[")[1].split()[1]
            print rt['DestinationNw'], "ubest/mbest: 1/0"+",", "Policy:", policy
            while rt_count > 0:
            	if rt['Protocol'] == "CONNECTED":
            		ip_int = self.swtch.getIPv4IntfState(rt_next['NextHopList'][rt_count-1]['NextHopIntRef']).json()	
                	print "   via",ip_int['Object']['IpAddr'].split("/")[0] +", "+rt_next['NextHopList'][rt_count-1]['NextHopIntRef']+", "+"["+str(rd['Distance'])+"/"+str(rt_next['NextHopList'][rt_count-1]['Weight'])+"]"+",",rt['RouteCreatedTime']+",",rt['Protocol']            		
            	else:  
                	print "   via", rt_next['NextHopList'][rt_count-1]['NextHopIp']+", "+rt_next['NextHopList'][rt_count-1]['NextHopIntRef']+", "+"["+str(rd['Distance'])+"/"+str(rt_next['NextHopList'][rt_count-1]['Weight'])+"]"+",",rt['RouteCreatedTime']+",",rt['Protocol']
                rt_count-=1

     

    def printIPv4IntfStates(self, IntfRef=None):
        ipv4intfs = self.swtch.getAllIPv4IntfStates()
        if len(ipv4intfs):
            print '------Ip Info------\n'
        for ipv4intf in ipv4intfs:
            if ipv4intf == IntfRef or IntfRef is None:
                print 'address: %s' %(ipv4intf['IntfRef'])

    def printIPv4IntfState(self, IntfRef):
        self.printIPv4IntfStates(IntfRef)

    def printVlanState(self, VlanId):

        found = self.printVlanStates(int(VlanId))
        if not found:
            print "VlanId %d NOT FOUND" % (VlanId,)

    def printVlanStates(self, VlanId=None):
        vlans = self.swtch.getAllVlanStates()
        if len(vlans):
            print '\n\n\t\t---- Vlans ----'
            print '%13s%12s%15s%10s' %('Vlan','Name','OperState','IfIndex')
        else:
            return 0
        for v in vlans:
            vlan = v['Object']
            if VlanId == None or vlan['VlanId'] == int(VlanId):
                print '%13s%12s%15s%10s\n' %(vlan['VlanId'], vlan['VlanName'], vlan['OperState'], vlan['IfIndex'])

        return 1

    def printPolicyStates (self) :
        policies = self.swtch.getObjects('PolicyDefinitionStates')
        if len(policies) :
            print '\n\n---- Policies----'
            print 'Name            Hit Counter     Affected Routes'
        for plcy in policies:
            routes=''
            for route in plcy['IpPrefixList']:
                routes = routes + '  ' +route
            print '%s       %s          %s ' %(plcy['Name'], 
                                plcy['HitCounter'],
                                routes)
                                
    def printDHCPHostStates (self) :
        hosts = self.swtch.getObjects('DhcpRelayHostDhcpStates')
        if len(hosts) :
            print '\n\n---- Hosts ----'
            print 'MacAddress  ServerIP   DiscoverSent@   OfferReceived@  RequestSent@  AckReceived@   OfferedIP   RequestedIP   AcceptedIP    GWIP   ClntTx  ClntRx  SvrRx  SvrTx'
        for host in hosts:
            print '%s   %s  %s   %s     %s   %s  %s   %s     %s   %s  %s   %s   %s  %s' %(
                        host['MacAddr'],
                        host['ServerIp'],
                        host['ClientDiscover'],
                        host['ServerOffer'],
                        host['ClientRequest'],
                        host['ServerAck'],
                        host['OfferedIp'],
                        host['RequestedIp'],
                        host['AcceptedIp'],
                        host['GatewayIp'],
                        host['ClientRequests'],
                        host['ClientResponses'],
                        host['ServerRequests'],
                        host['ServerResponses'])




    def printVlans (self):
        vlans = self.swtch.getObjects('Vlans')
        if len(vlans):
            print '\n\n---- Vlans ----'
            print 'VlanId  Name   IfIndex   TaggedPorts     UntaggedPorts       Status'
        for vlan in vlans:
            print '%s   %s  %s  %s   %s  %s' %(vlan ['VlanId'],
                                               vlan ['VlanName'],
                                               vlan ['IfIndex'],
                                               vlan ['IfIndexList'],
                                               vlan ['UntagIfIndexList'],
                                               vlan ['OperState'])

    def printVrrpIntfState (self):
        vrids = self.swtch.getObjects('VrrpIntfStates')
        '''
	entry.IfIndex = gblInfo.IntfConfig.IfIndex
	entry.VRID = gblInfo.IntfConfig.VRID
	entry.IntfIpAddr = gblInfo.IpAddr
	entry.Priority = gblInfo.IntfConfig.Priority
	entry.VirtualIPv4Addr = gblInfo.IntfConfig.VirtualIPv4Addr
	entry.AdvertisementInterval = gblInfo.IntfConfig.AdvertisementInterval
	entry.PreemptMode = gblInfo.IntfConfig.PreemptMode
	entry.VirtualRouterMACAddress = gblInfo.IntfConfig.VirtualRouterMACAddress
	entry.SkewTime = gblInfo.SkewTime
	entry.MasterDownInterval = gblInfo.MasterDownInterval
        '''
        if len(vrids):
            print ''
            print 'IfIndex   VRID    Vip     Priority   State     ViMac              IntfIp      Preempt  Advertise    Skew  Master_Down'
            print '================================================================================================================'
            for fObject in vrids:
                entry = fObject['Object']
                print '%s   %s  %s     %s   %s   %s      %s   %s    %s            %s      %s' %(entry ['IfIndex'],
                                                                   entry ['VRID'],
                                                                   entry ['VirtualIPv4Addr'],
                                                                   entry ['Priority'],
                                                                   entry ['VrrpState'],
                                                                   entry ['VirtualRouterMACAddress'],
                                                                   entry ['IntfIpAddr'],
                                                                   entry ['PreemptMode'],
                                                                   entry ['AdvertisementInterval'],
                                                                   entry ['SkewTime'],
                                                                   entry ['MasterDownTimer'])
            print ''

    def printOspfLsdb(self) :
        lsas = self.swtch.getObjects('OspfLsdbEntryStates')
        if len(lsas) :
            print '\n\n---- Link State DB----'
            print 'LSA Type LS Checksum     LS Age      LS AreaId       LS ID       LS Sequence     LS RouterId     LS Advertisement'
        count = 0
        for lsa in lsas:
            count = count + 1
            print 'LS Database Entry Number:', count
            #print '%s           %s          %s          %s      %s      %s      %s      %s' %(lsa ['LsdbType'],
             #                                                               lsa ['LsdbChecksum'],
             #                                                               lsa ['LsdbAge'],
             #                                                               lsa ['LsdbAreaId'],
             #                                                               lsa ['LsdbLsid'],
             #                                                               lsa ['LsdbSequence'],
             #                                                               lsa ['LsdbRouterId'],
              #                                                              lsa ['LsdbAdvertisement'])
            adv = lsa['LsdbAdvertisement'].split(':')
            #print adv
            if lsa['LsdbType'] == 1 :
                print "LS Type: Router LSA"
            elif lsa['LsdbType'] == 2 :
                print "LS Type: Network LSA"
            elif lsa['LsdbType'] == 3 :
                print "LS Type: Summary Type 3 LSA"
            elif lsa['LsdbType'] == 4 :
                print "LS Type: Summary Type 4 LSA"
            elif lsa['LsdbType'] == 5 :
                print "LS Type: AS External LSA"

            print 'LS Age:', lsa ['LsdbAge']
            print 'Link State Id:', lsa ['LsdbLsid']
            print 'Advertising Router:', lsa ['LsdbRouterId']
            print 'LS Sequence Number:', lsa ['LsdbSequence']
            print 'LS Checksum:', lsa ['LsdbChecksum']
            if lsa['LsdbType'] == 1 :
                options = int(adv[0])
                if options & 0x1 :
                    print 'Bit B : true'
                else :
                    print 'Bit B : false'
                if options & 0x2 :
                    print 'Bit E : true'
                else :
                    print 'Bit E : false'
                if options & 0x4 :
                    print 'Bit V : true'
                else :
                    print 'Bit V : false'
                numOfLinks = int(adv[2]) << 8 | int(adv[3])
                print 'Number of Links:', numOfLinks
                for i in range(0, numOfLinks) :
                    print '         Link Number:', i+1
                    linkId = adv[4 + (i * 12)] + '.' + adv[4 + (i * 12) + 1] + '.' + adv[4 + (i * 12) + 2] + '.' + adv[4 + (i * 12) + 3]
                    print '         Link ID:', linkId
                    linkData = adv[4 + (i * 12) + 4] + '.' + adv[4 + (i * 12) + 5] + '.' + adv[4 + (i * 12) + 6] + '.' + adv[4 + (i * 12) + 7]
                    print '         Link Data:', linkData
                    linkType = ""
                    lType = adv[4 + (i * 12) + 8]
                    if lType == '1' :
                        linkType = "Point-to-Point Connection"
                    elif lType == '2' :
                        linkType = "Transit Link" 
                    elif lType == '3' :
                        linkType = "Stub Link" 
                    elif lType == '4' :
                        linkType = "Virtual Link" 
                    print '         Link Type:', linkType
                    numOfTOS = int(adv[4 + (i * 12) + 9])
                    print '         Number of TOS:', numOfTOS
                    metric = int(adv[4 + (i * 12) + 10]) << 8 | int(adv[4 + (i * 12) + 11])
                    print '         Metric:', metric
                    print ''
            elif lsa['LsdbType'] == 2 :
                netmask = adv[0] + '.' + adv[1] + '.' + adv[2] + '.' + adv[3]
                print 'Netmask:', netmask
                for i in range(0, (len(adv) - 4) / 4) :
                    attachedRtr = adv[4 + i * 4] + '.' + adv[5 + i * 4] + '.' + adv[6 + i * 4] + '.' + adv[3 + i * 4]
                    print '         Attached Router:', attachedRtr
                    
            print ''

    def printStpBridges(self):

        brgs = self.swtch.getObjects('StpBridgeStates')

        if len(brgs):
            print '\n\n---- STP Bridge DB----'

            count = 0
            for data in brgs:
                obj = data['Object']
                print "BrgIfIndex: ", obj["IfIndex"]
                #print "Version: ", obj["ForceVersion"]
                print "Bridge Id: ", obj["Address"]
                print "Bridge Hello time: ", obj["BridgeHelloTime"]
                print "Bridge TxHold: ", obj["TxHoldCount"]
                print "Bridge Forwarding Delay: ", obj["BridgeForwardDelay"]
                print "Bridge Max Age: ", obj["BridgeMaxAge"]
                print "Bridge Priority: ", obj["Priority"]
                print "Time Since Topology Change: UNSUPPORTED" #nextStpBridgeState.Dot1dStpTimeSinceTopologyChange uint32 //The time (in hundredths of a second) since the last time a topology change was detected by the bridge entity. For RSTP, this reports the time since the tcWhile timer for any port on this Bridge was nonzero.
                print "Topology Changes: UNSUPPORTED" #nextStpBridgeState.Dot1dStpTopChanges              uint32 //The total number of topology changes detected by this bridge since the management entity was last reset or initialized.
                print "Root Bridge Id: ", obj["DesignatedRoot"]
                print "Root Cost: ", obj["RootCost"]
                print "Root Port: ", obj["RootPort"]
                print "Max Age: ", obj["MaxAge"]
                print "Hello Time: ", obj["HelloTime"]
                print "Hold Time: UNSUPPORTED" #Dot1dStpHoldTime = int32(b.TxHoldCount)
                print "Forwarding Delay: ", obj["ForwardDelay"]
                print "Bridge Vlan: ", obj["Vlan"] if obj["Vlan"] != 0 else "DEFAULT"
                print "=====================================================================================\n\n"

    def printStpPorts(self):
        stateDict = {
            1 : "Disabled",
            2 : "Blocked",
            3 : "Listening",
            4 : "Learning",
            5 : "Forwarding",
            6 : "Broken",
        }
        linkTypeDict = {
            0 : "LAN",
            1 : "P2P",
        }

        ports = self.swtch.getObjects('StpPortStates')

        if len(ports):
            print '\n\n---- STP PORT DB----'
            for data in ports:
                obj = data['Object']
                bainconsistant = "(inconsistant)" if obj["BridgeAssuranceInconsistant"] else ""
                print "IfIndex %s of BrgIfIndex %s is %s %s" %(obj["IfIndex"], obj["BrgIfIndex"], stateDict[obj["State"]], bainconsistant)
                #print "Enabled %s, Protocol Migration %s" %(obj["Enable"], obj["ProtocolMigration"])
                print "Enabled %s" %(obj["Enable"],)
                print "Port path cost %s, Port priority %s, Port Identifier %s" %(obj["PathCost32"], obj["Priority"], obj["IfIndex"])
                print "Designated root has bridge id %s" %(obj["DesignatedRoot"])
                print "Designated bridge has bridge id %s" %(obj["DesignatedBridge"])
                print "Designated port id %s, designated path cost %s admin path cost %s" %(obj["DesignatedPort"], obj["DesignatedCost"], obj["AdminPathCost"])
                print "Root Timers: max age %s, forward delay %s, hello %s" %(obj["MaxAge"],obj["ForwardDelay"],obj["HelloTime"],)
                print "Number of transitions to forwarding state: %s" %(obj["ForwardTransitions"],)
                print "AdminEdge %s OperEdge %s" %(obj["AdminEdgePort"], obj["OperEdgePort"])
                print "Bridge Assurance %s Bpdu Guard %s" %(obj["BridgeAssurance"], obj["BpduGuard"])
                print "Link Type %s" %("UNSUPPORTED",)
                print "\nPort Timers: (current tick(seconds) count)"
                print "EdgeDelayWhile:\t", obj["EdgeDelayWhile"]
                print "FdWhile:       \t", obj["FdWhile"]
                print "HelloWhen:     \t", obj["HelloWhen"]
                print "MdelayWhile:   \t", obj["MdelayWhile"]
                print "RbWhile:       \t", obj["RbWhile"]
                print "RcvdInfoWhile  \t", obj["RcvdInfoWhile"]
                print "RrWhile:       \t", obj["RrWhile"]
                print "TcWhile:       \t", obj["TcWhile"]
                print "\nCounters:"
                print "        %13s%13s" %("RX", "TX")
                print "BPDU    %13s%13s" %(obj["BpduInPkts"], obj["BpduOutPkts"])
                print "STP     %13s%13s" %(obj["StpInPkts"], obj["StpOutPkts"])
                print "TC      %13s%13s" %(obj["TcInPkts"], obj["TcOutPkts"])
                print "TC ACK  %13s%13s" %(obj["TcAckInPkts"], obj["TcAckOutPkts"])
                print "RSTP    %13s%13s" %(obj["RstpInPkts"], obj["RstpOutPkts"])
                print "PVST    %13s%13s" %(obj["PvstInPkts"], obj["PvstOutPkts"])
                print "\nFSM States:"
                print "PIM - Port Information, PRTM - Port Role Transition, PRXM - Port Receive"
                print "PSTM - Port State Transition, PPM - Port Protocol Migration, PTXM - Port Transmit"
                print "PTIM - Port Timer, BDM - Bridge Detection, TCM - Topology Change"
                print "MACHINE       %20s%20s" %("CURRENT", "PREVIOUS")
                print "PIM           %20s%20s" %(obj["PimCurrState"], obj["PimPrevState"])
                print "PRTM          %20s%20s" %(obj["PrtmCurrState"], obj["PrtmPrevState"])
                print "PRXM          %20s%20s" %(obj["PrxmCurrState"], obj["PrxmPrevState"])
                print "PSTM          %20s%20s" %(obj["PstmCurrState"], obj["PstmPrevState"])
                print "PPM           %20s%20s" %(obj["PpmCurrState"], obj["PpmPrevState"])
                print "PTXM          %20s%20s" %(obj["PtxmCurrState"], obj["PtxmPrevState"])
                print "PTIM          %20s%20s" %(obj["PtimCurrState"], obj["PtimPrevState"])
                print "BDM           %20s%20s" %(obj["BdmCurrState"], obj["BdmPrevState"])
                print "TCM           %20s%20s" %(obj["TcmCurrState"], obj["TcmPrevState"])
                print "====================================================================="


    def printLaPortChannelMembers(self):

        # YANG MODEL REPRESENTATION
        RxMachineStateDict = {
            0 : "RX_CURRENT",
            1 : "RX_EXPIRED",
            2 : "RX_DEFAULTED",
            3 : "RX_INITIALIZE",
            4 : "RX_LACP_DISABLED",
            5 : "RX_PORT_DISABLE",
        }

        MuxMachineStateDict = {
            0 : "MUX_DETACHED",
            1 : "MUX_WAITING",
            2 : "MUX_ATTACHED",
            3 : "MUX_COLLECTING",
            4 : "MUX_DISTRIBUTING",
            5 : "MUX_COLLECTING_DISTRIBUTING",
        }

        ChurnMachineStateDict = {
            0 : "CDM_NO_CHURN",
            1 : "CDM_CHURN",
        }

        '''
        //Collecting bool
        // parent leaf
        //OperKey uint16
        // parent leaf
        //PartnerId string
        // parent leaf
        //Interface string
        // parent leaf
        //Synchronization int32
        // parent leaf
        //Aggregatable bool
        // parent leaf
        Mtu uint16
        // parent leaf
        //LacpMode int32
        // parent leaf
        //PartnerKey uint16
        // parent leaf
        Description string
        // parent leaf
        //SystemIdMac string
        // parent leaf
        //LagType int32
        // parent leaf
        //SystemId string
        // parent leaf
        //Interval int32
        // parent leaf
        //Enabled bool
        // parent leaf
        //NameKey string `SNAPROUTE: KEY`
        // parent leaf
        //Distributing bool
        // parent leaf
        //Timeout int32
        // parent leaf
        //Activity int32
        // parent leaf
        //SystemPriority uint16
        // parent leaf
        Type string
        // parent leaf
        MinLinks uint16
        //yang_name: lacp-in-pkts class: leaf
        //LacpInPkts uint64
        //yang_name: lacp-out-pkts class: leaf
        //LacpOutPkts uint64
        //yang_name: lacp-rx-errors class: leaf
        //LacpRxErrors uint64
        //yang_name: lacp-tx-errors class: leaf
        //LacpTxErrors uint64
        //yang_name: lacp-unknown-errors class: leaf
        //LacpUnknownErrors uint64
        //yang_name: lacp-errors class: leaf
        //LacpErrors uint64
        '''

        members = self.swtch.getAllLaPortChannelMemberStates()

        for data in members:
            d = data['Object']

            print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n'
            print 'IfIndex: ' + "%s" % d['IfIndex'] + 'LagId: ' + "%s" %d['LagId'] + 'LagIfIndex: ' + "%s" %d['LagIfIndex']
            print 'OperState: ' + d['OperState']
            #print 'lagtype: ' + ('LACP' if not d['LagType'] else 'STATIC')
            print 'operkey: %s' % d['OperKey']
            #print 'mode: ' + ('ACTIVE' if not d['LacpMode'] else 'PASSIVE')
            #print 'interval: %s' % (('SLOW' if d['Interval'] else 'FAST'))
            #print 'system:\n'
            #print '\tsystemmac: %s' % d['SystemIdMac']
            #print '\tsysteprio: %s' % d['SystemPriority']
            #print '\tsystemId: %s' % d['SystemId']
            print 'actor:'
            stateStr = '\tstate: '
            for s in ('Activity', 'Timeout', 'Aggregatable', 'Synchronization', 'Collecting', 'Distributing', 'Defaulted'):
                if s == 'Synchronization' and not d[s]:
                    stateStr += s + ', '
                elif s == 'Activity' and not d[s]:
                    stateStr += s + ', '
                elif s in ('Activity', 'Synchronization'):
                    continue
                elif d[s]:
                    stateStr += s + ', '
            print stateStr.rstrip(',')

            print '\tstats:'
            for s in ('LacpInPkts', 'LacpOutPkts', 'LacpRxErrors', 'LacpTxErrors', 'LacpUnknownErrors', 'LacpErrors', 'LampInPdu', 'LampOutPdu', 'LampInResponsePdu', 'LampOutResponsePdu'):
                print '\t' + s, ': ', d[s]

            print 'partner:\n'
            print '\t' + 'key: %s' % d['PartnerKey']
            print '\t' + 'partnerid: ' + d['PartnerId']

            print 'debug:\n'
            try:
                print '\t' + 'debugId: %s' % d['DebugId']
                print '\t' + 'RxMachineState: %s' % RxMachineStateDict[d['RxMachine']]
                print '\t' + 'RxTime (rx pkt rcv): %s' % d['RxTime']
                print '\t' + 'MuxMachineState: %s' % MuxMachineStateDict[d['MuxMachine']]
                print '\t' + 'MuxReason: %s' % d['MuxReason']
                print '\t' + 'Actor Churn State: %s' % ChurnMachineStateDict[d['ActorChurnMachine']]
                print '\t' + 'Partner Churn State: %s' % ChurnMachineStateDict[d['PartnerChurnMachine']]
                print '\t' + 'Actor Churn Count: %s' % d['ActorChurnCount']
                print '\t' + 'Partner Churn Count: %s' % d['PartnerChurnCount']
                print '\t' + 'Actor Sync Transition Count: %s' % d['ActorSyncTransitionCount']
                print '\t' + 'Partner Sync Transition Count: %s' % d['PartnerSyncTransitionCount']
                print '\t' + 'Actor LAG ID change Count: %s' % d['ActorChangeCount']
                print '\t' + 'Partner LAG ID change Count: %s' % d['PartnerChangeCount']
            except Exception as e:
                print e


    # TODO fix cli so that the name is better
    def printBGPRouteStates(self, ):
        routes = self.swtch.getAllBGPRouteStates()
        print '\n\n---- BGP Routes ----'
        labels = ('Network', 'NextHop', 'Metric', 'LocalPref', 'Updated', 'Path')
        rows = []
        for r in routes:
            rt = r['Object']
            if rt['Path'] is None:
               bgp_path =  rt['Path']
            else:
               bgp_path = [x.encode('utf-8') for x in rt['Path']]
            rows.append((rt['Network']+"/"+str(rt['CIDRLen']),
                        "%s" %(rt['NextHop']),
                        "%s" %(rt['Metric']),
                        "%s" %(rt['LocalPref']),
                        "%s" %(rt['UpdatedDuration'].split(".")[0]),
                        "%s" %( bgp_path )))
        width = 30
        print indent([labels]+rows, hasHeader=True, separateRows=False,
                     prefix=' ', postfix=' ', headerChar= '-', delim='    ',
                     wrapfunc=lambda x: wrap_onspace_strict(x,width))

    def printIPv4IntfStates(self,):
        ipintfs = self.swtch.getAllIPv4IntfStates()
        print '\n\n---- IP Interfaces ----'
        labels = ('Interface', 'IfIndex', 'Address', 'OperState', 'L2IntfType', 'L2IntfId')
        rows = []
        for i in ipintfs:
            ip = i['Object']
            rows.append((ip['IntfRef'],
                        "%s" %(ip['IfIndex']),
                        "%s" %(ip['IpAddr']),
                        "%s" %(ip['OperState']),
                        "%s" %(ip['L2IntfType']),
                        "%s" %(ip['L2IntfId'])))
        width = 20
        print indent([labels]+rows, hasHeader=True, separateRows=False,
                     prefix=' ', postfix=' ', headerChar= '-', delim='    ',
                     wrapfunc=lambda x: wrap_onspace_strict(x,width))

        labels = ('NumUpEvents', 'LastUpEventTime', 'NumDownEvents', 'LastDownEventtime')
        rows = []
        for i in ipintfs:
            ip = i['Object']
            rows.append(("%s" %(ip['NumUpEvents']),
                        "%s" %(ip['LastUpEventTime']),
                        "%s" %(ip['NumDownEvents']),
                        "%s" %(ip['LastDownEventTime'])))
        width = 20
        print indent([labels]+rows, hasHeader=True, separateRows=False,
                     prefix=' ', postfix=' ', headerChar= '-', delim='    ',
                     wrapfunc=lambda x: wrap_onspace_strict(x,width))


    def printBGPNeighborStates(self):	   
		   sessionState=  {  1: "Idle",
				     2: "Connect",
				     3: "Active",
				     4: "OpenSent",
				     5: "OpenConfirm",
				     6: "Established"
				   } 
	
		   peers = self.swtch.getAllBGPNeighborStates()
		   if len(peers)>=0: 
			   print '\n'
			   labels = ('Neighbor','LocalAS','PeerAS','State','RxMsg','TxMsg','Description','Prefixes_Rcvd')
			   rows=[]
			   for p in peers:
			       pr = p['Object']
			       RXmsg = (pr['Messages']['Received']['Notification']) + (pr['Messages']['Received']['Update'])
			       TXmsg = (pr['Messages']['Sent']['Notification']) + (pr['Messages']['Sent']['Update'])
			       rows.append( (pr['NeighborAddress'],
						 "%s" %(pr['LocalAS']),
						 "%s" %(pr['PeerAS']),
						 "%s" %(sessionState[pr['SessionState']]),
						 "%s" %(RXmsg),
						 "%s" %(TXmsg),
						 "%s" %(pr['Description']),
						 "%s" %(pr['TotalPrefixes'])))
			   width = 20
			   print indent([labels]+rows, hasHeader=True, separateRows=False,
                     		prefix=' ', postfix=' ', headerChar= '-', delim='    ',
                     		wrapfunc=lambda x: wrap_onspace_strict(x,width))
コード例 #10
0
ファイル: flexprint.py プロジェクト: ashutoshshanker/flexSdk
 def  __init__ (self, ip, port):
     self.swtch = FlexSwitch(ip, port)
コード例 #11
0
ファイル: monitornw.py プロジェクト: zirben0/apps
                        action='store',
                        nargs='?',
                        default='localhost',
                        help='Ip Address of the node')

    parser.add_argument('--port',
                        type=str,
                        dest='port',
                        action='store',
                        nargs='?',
                        default='8080',
                        help='Port')

    args = parser.parse_args()

    restIf = FlexSwitch(args.ip, args.port)
    portDict = {}
    while True:
        portsInfo = restIf.getAllPortStates()
        for port in portsInfo:
            portName = port['Object']['Name']
            portStat = portDict.get(port['Object']['Name'], None)
            if portStat == None:
                portStat = PortStat()
                portDict[port['Object']['Name']] = portStat

            portStat.updateDiscardCounts(port['Object']['IfInDiscards'])
            discardRate = portStat.getDiscardRate(5)
            if port['Object']['IfInDiscards']:
                print 'Port %s Discard Count %s ' % (
                    portName, port['Object']['IfInDiscards'])
コード例 #12
0
ファイル: snap_commands.py プロジェクト: zirben0/apps
 def __init__(self, switch_ip):
     self.switch_ip = switch_ip
     self.swtch = FlexSwitch(self.switch_ip, 8080)
コード例 #13
0
ファイル: snap_commands.py プロジェクト: zirben0/apps
class FlexSwitch_info():
    def __init__(self, switch_ip):
        self.switch_ip = switch_ip
        self.swtch = FlexSwitch(self.switch_ip, 8080)

    def displayRunBGP(self):
        neigh = self.swtch.getObjects('BGPNeighborStates')
        #globalc = self.swtch.getObjects('BGPGlobals')
        #peers = self.swtch.getObjects('BGPPeerGroups')

        #if len(globalc)>=0:
        #    print globalc

        if len(neigh) >= 0:
            print neigh

        #if len(peers)>=0:
        #    print peers

    def displayBGPPeers(self):
        sessionState = {
            0: "Idle",
            1: "Connect",
            2: "Active",
            3: "OpenSent",
            4: "OpenConfirm",
            5: "Established"
        }

        peers = self.swtch.getObjects('BGPNeighborStates')
        if len(peers) >= 0:
            print '\n'
            print 'Neighbor   LocalAS   PeerAS     State      RxNotifications    RxUpdates   TxNotifications TxUpdates  Description'
        for pr in peers:
            print '%s %s %s     %s       %s              %s              %s           %s	%s' % (
                pr['Object']['NeighborAddress'].ljust(12),
                str(pr['Object']['LocalAS']).ljust(8), pr['Object']['PeerAS'],
                sessionState[int(pr['Object']['SessionState'] - 1)],
                pr['Object']['Messages']['Received']['Notification'],
                pr['Object']['Messages']['Received']['Update'],
                pr['Object']['Messages']['Sent']['Notification'],
                pr['Object']['Messages']['Sent']['Update'],
                pr['Object']['Description'])

        print "\n"

    def displayBGPtable(self):
        routes = self.swtch.getObjects('BGPRoutes')
        if len(routes) >= 0:
            print '\n'
            print 'Network          Mask           NextHop          Metric     LocalPref      Updated   		Path'
        for rt in routes:
            print '%s %s %s %4d   %9d    %14s   %13s' % (
                rt['Object']['Network'].ljust(17), str(
                    rt['Object']['CIDRLen']).ljust(13),
                rt['Object']['NextHop'].ljust(15), rt['Object']['Metric'],
                rt['Object']['LocalPref'],
                rt['Object']['UpdatedDuration'].split(".")[0],
                rt['Object']['Path'])
        print "\n"

    def displayBfdNeigh(self):
        neigh = self.swtch.getObjects('BfdSessionStates')
        if len(neigh) >= 0:
            print "BFD Neighbors"
            print "********************************************************************************************"
        for rt in neigh:
            print 'Session ID:', rt['Object']['SessionId']
            print 'Interface:'
            print 'IfIndex:', rt['Object']['IfIndex']
            print 'LocalIP:', rt['Object']['LocalIpAddr']
            print 'Remote IP:', rt['Object']['IpAddr']
            print 'Local State:', rt['Object']['SessionState']
            print 'Remote State:', rt['Object']['RemoteSessionState']
            print 'Local Descrim:', rt['Object']['LocalDiscriminator']
            print 'Remote Descrim:', rt['Object']['RemoteDiscriminator']
            print 'TxPackets:', rt['Object']['NumTxPackets']
            print 'RxPackets:', rt['Object']['NumRxPackets']
            print 'Multiplier:', rt['Object']['DetectionMultiplier']
            print 'MinTxInt:', rt['Object']['DesiredMinTxInterval']
            print 'MinRxInt:', rt['Object']['RequiredMinRxInterval']
            print 'LocalDiag:', rt['Object']['LocalDiagType']
            print 'RegisteredProtocols:', rt['Object']['RegisteredProtocols']
            print "********************************************************************************************"

        print "\n"

    def displayBfdInt(self):
        int = self.swtch.getObjects('BfdInterfaceStates')
        if len(int) >= 0:
            print 'BFD Interfaces'
            print "********************************************************************************************"
        for rt in int:
            print 'Interface:',
            print 'IfIndex:', rt['Object']['IfIndex']
            print 'Enabled:', rt['Object']['Enabled']
            print 'NumSessions:', rt['Object']['NumSessions']
            print 'Multiplier:', rt['Object']['LocalMultiplier']
            print 'MinTxInt:', rt['Object']['DesiredMinTxInterval']
            print 'MinRxInt:', rt['Object']['RequiredMinRxInterval']
            print "********************************************************************************************"

        print "\n"

    def displayRoutes(self):
        routes = self.swtch.getObjects('IPv4RouteStates')
        if len(routes) >= 0:
            print '\n'
            print 'Network         NextHop         Protocol         IfType         IfIndex'
        for rt in routes:
            print '%s %s %s   %s    %s ' % (
                rt['Object']['DestinationNw'].ljust(15),
                rt['Object']['NextHopIp'].ljust(15),
                rt['Object']['Protocol'].ljust(15),
                rt['Object']['OutgoingIntfType'].ljust(15),
                rt['Object']['OutgoingInterface'].ljust(15))
        print "\n"

    def displayARPEntries(self):
        arps = self.swtch.getObjects('ArpEntryStates')
        if len(arps) >= 0:
            print '\n'
            print 'IP Address	MacAddress   	    TimeRemaining  	Vlan 	  Intf'
        for d in arps:
            print '%s	%s    %s	 %s	%s' % (
                d['Object']['IpAddr'], d['Object']['MacAddr'],
                d['Object']['ExpiryTimeLeft'], d['Object']['Vlan'],
                d['Object']['Intf'])
        print "\n"

    def IPv4Intfstatus(self):
        ip_int = self.swtch.getObjects('IPv4IntfStates')
        if len(ip_int) >= 0:
            print '\n'
            print 'Interface     IfIndex        IPv4'
        for d in ip_int:
            if len(str(d['Object']['IfIndex'])) < 8:
                if d['Object']['IfIndex'] < 73:
                    index = self.swtch.getObjects('PortStates')
                    for e in index:
                        if e['Object']['IfIndex'] == d['Object']['IfIndex']:
                            port = e['Object']['Name']
                            break
                        else:
                            port = 'N/A'
                else:
                    index = self.swtch.getObjects('Vlans')
                    for e in index:
                        if e['Object']['IfIndex'] == d['Object']['IfIndex']:
                            port = e['Object']['VlanName']
                            break
                        else:
                            port = 'N/A'

                print '%s %6s %21s' % (port.ljust(10), d['Object']['IfIndex'],
                                       d['Object']['IpAddr'])
            elif len(str(d['Object']['IfIndex'])) >= 8:
                if d['Object']['IfIndex'] < 73:
                    index = self.swtch.getObjects('PortStates')
                    for e in index:
                        if e['Object']['IfIndex'] == d['Object']['IfIndex']:
                            port = e['Object']['Name']
                            break
                        else:
                            port = 'N/A'
                else:
                    index = self.swtch.getObjects('VlanStates')
                    for e in index:
                        if e['Object']['IfIndex'] == d['Object']['IfIndex']:
                            port = e['Object']['VlanName']
                            break
                        else:
                            port = 'N/A'

                print '%s %s %13s' % (port.ljust(10), d['Object']['IfIndex'],
                                      d['Object']['IpAddr'])

        print "\n"

    def displayPortObjects(self):
        ports = self.swtch.getObjects('PortStates')
        if len(ports):
            print '\n'
            print 'Port         InOctets   InUcastPkts   InDiscards  InErrors     InUnknownProtos   OutOctets OutUcastPkts   OutDiscards   OutErrors'
        for d in ports:
            if d['Object']['IfIndex'] == 0:
                continue
            elif d['Object']['IfIndex'] < 10:
                print '%s  %8d %10d   %10d    %8d   %15d   %9d   %12d   %11d   %11d' % (
                    "fpPort-" + str(d['Object']['IfIndex']),
                    d['Object']['IfInOctets'], d['Object']['IfInUcastPkts'],
                    d['Object']['IfInDiscards'], d['Object']['IfInErrors'],
                    d['Object']['IfInUnknownProtos'],
                    d['Object']['IfOutOctets'], d['Object']['IfOutUcastPkts'],
                    d['Object']['IfOutDiscards'], d['Object']['IfOutErrors'])
            else:
                print '%s  %7d %10d   %10d    %8d   %15d   %9d   %12d   %11d   %11d' % (
                    "fpPort-" + str(d['Object']['IfIndex']),
                    d['Object']['IfInOctets'], d['Object']['IfInUcastPkts'],
                    d['Object']['IfInDiscards'], d['Object']['IfInErrors'],
                    d['Object']['IfInUnknownProtos'],
                    d['Object']['IfOutOctets'], d['Object']['IfOutUcastPkts'],
                    d['Object']['IfOutDiscards'], d['Object']['IfOutErrors'])
        print "\n"

    def displayCPUPortObjects(self):
        ports = self.swtch.getObjects('PortStates')
        if len(ports):
            print '\n'
            print 'Port         InOctets   InUcastPkts   InDiscards  InErrors     InUnknownProtos   OutOctets OutUcastPkts   OutDiscards   OutErrors'
        for d in ports:
            if d['Object']['IfIndex'] == 0:
                print '%s  %8d %10d   %10d    %8d   %15d   %9d   %12d   %11d   %11d' % (
                    "CPU", d['Object']['IfInOctets'],
                    d['Object']['IfInUcastPkts'], d['Object']['IfInDiscards'],
                    d['Object']['IfInErrors'],
                    d['Object']['IfInUnknownProtos'],
                    d['Object']['IfOutOctets'], d['Object']['IfOutUcastPkts'],
                    d['Object']['IfOutDiscards'], d['Object']['IfOutErrors'])

    def displayPortStatus(self):
        ports = self.swtch.getObjects('PortStates')
        if len(ports):
            print '\n'
            print 'Port         Status   IFIndex   Duplex   Speed     Type'
        for d in ports:
            if d['Object']['IfIndex'] == 0:
                continue
            elif d['Object']['IfIndex'] < 10:
                print '%s  %8s %6s %10s %8s %9s' % (
                    "fpPort-" + str(d['Object']['IfIndex']),
                    d['Object']['OperState'], d['Object']['IfIndex'], 'N/A',
                    'N/A', 'N/A')
            else:
                print '%s  %7s %6s %10s %8s %9s' % (
                    "fpPort-" + str(d['Object']['IfIndex']),
                    d['Object']['OperState'], d['Object']['IfIndex'], 'N/A',
                    'N/A', 'N/A')

    def displayVlanInfo(self, vlanId=0):
        if vlanId == 0:
            vlans = self.swtch.getObjects('Vlans')
            if len(vlans):
                print 'Vlan    Ports 	Untagged_Ports'
            for d in vlans:
                print '%s  %8s %8s ' % (str(
                    d['Object']['VlanId']), d['Object']['IfIndexList'],
                                        d['Object']['UntagIfIndexList'])
        else:
            vlans = self.swtch.getObjects('Vlans')
            if len(vlans):
                print 'Vlan    Ports 	Untagged_Ports'
            found = 0
            for d in vlans:
                if d['Object']['VlanId'] == int(vlanId):
                    found = 1
                    print '%s  %8s %8s ' % (str(
                        d['Object']['VlanId']), d['Object']['IfIndexList'],
                                            d['Object']['UntagIfIndexList'])
            if found == 0:
                print "**Vlan doesn't Exist**"

    def verifyDRElectionResult(self):
        ospfIntfs = self.swtch.getObjects('OspfIfEntryStates')
        print '\n'
        #self.assertNotEqual(len(ospfIntfs) != 0)
        if len(ospfIntfs) >= 0:
            print 'IfAddr IfIndex  State  DR-RouterId DR-IpAddr BDR-RouterI BDR-IpAddr NumEvents LSACount LSACksum'

        for d in ospfIntfs:
            #if sum(d['ospfIntfs']):
            print '%3s  %3d %10s   %10s    %8s   %15s   %9s   %12s   %11s   %11s' % (
                d['Object']['IfIpAddressKey'], d['Object']['AddressLessIfKey'],
                d['Object']['IfState'], d['Object']['IfDesignatedRouter'],
                d['Object']['IfBackupDesignatedRouter'],
                d['Object']['IfEvents'], d['Object']['IfLsaCount'],
                d['Object']['IfLsaCksumSum'],
                d['Object']['IfDesignatedRouterId'],
                d['Object']['IfBackupDesignatedRouterId'])
        print "\n"

    def getLagMembers(self):
        members = self.swtch.getObjects('AggregationLacpMemberStateCounterss')
        print '\n---- LACP Members----'
        if len(members):
            for d in members:
                print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n'
                print 'name: ' + d['Object']['NameKey'] + ' interface: ' + d[
                    'Object']['Interface']
                print 'enabled: %s' % d['Object']['Enabled']
                print 'lagtype: ' + ('LACP' if not d['LagType'] else 'STATIC')
                print 'operkey: %s' % d['Object']['OperKey']
                print 'mode: ' + ('ACTIVE' if not d['Object']['LacpMode'] else
                                  'PASSIVE')
                print 'interval: %s' % (
                    ('SLOW' if d['Object']['Interval'] else 'FAST'))
                print 'system:\n'
                print '\tsystemmac: %s' % d['Object']['SystemIdMac']
                print '\tsysteprio: %s' % d['Object']['SystemPriority']
                print '\tsystemId: %s' % d['Object']['SystemId']
                print 'actor:'
                stateStr = '\tstate: '
                for s in ('Activity', 'Timeout', 'Aggregatable',
                          'Synchronization', 'Collecting', 'Distributing'):
                    if s == 'Synchronization' and not d['Object'][s]:
                        stateStr += s + ', '
                    elif s == 'Activity' and not d['Object'][s]:
                        stateStr += s + ', '
                    elif s in ('Activity', 'Synchronization'):
                        continue
                    elif d[s]:
                        stateStr += s + ', '
                print stateStr.rstrip(',')

                print '\tstats:'
                for s in ('LacpInPkts', 'LacpOutPkts', 'LacpRxErrors',
                          'LacpTxErrors', 'LacpUnknownErrors', 'LacpErrors',
                          'LampInPdu', 'LampOutPdu', 'LampInResponsePdu',
                          'LampOutResponsePdu'):
                    print '\t' + s, ': ', d['Object'][s]

                print 'partner:\n'
                print '\t' + 'key: %s' % d['Object']['PartnerKey']
                print '\t' + 'partnerid: ' + d['Object']['PartnerId']

    def getLagMembers_detail(self):
        RxMachineStateDict = {
            0: "RX_CURRENT",
            1: "RX_EXPIRED",
            2: "RX_DEFAULTED",
            3: "RX_INITIALIZE",
            4: "RX_LACP_DISABLED",
            5: "RX_PORT_DISABLE",
        }

        MuxMachineStateDict = {
            0: "MUX_DETACHED",
            1: "MUX_WAITING",
            2: "MUX_ATTACHED",
            3: "MUX_COLLECTING",
            4: "MUX_DISTRIBUTING",
            5: "MUX_COLLECTING_DISTRIBUTING",
        }

        ChurnMachineStateDict = {
            0: "CDM_NO_CHURN",
            1: "CDM_CHURN",
        }
        members = self.swtch.getObjects('AggregationLacpMemberStateCounterss')
        print '\n---- LACP Members----'
        if len(members):
            for d in members:
                print '+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n'
                print 'name: ' + d['Object']['NameKey'] + ' interface: ' + d[
                    'Interface']
                print 'enabled: %s' % d['Object']['Enabled']
                print 'lagtype: ' + ('LACP' if not d['Object']['LagType'] else
                                     'STATIC')
                print 'operkey: %s' % d['Object']['OperKey']
                print 'mode: ' + ('ACTIVE' if not d['Object']['LacpMode'] else
                                  'PASSIVE')
                print 'interval: %s' % (
                    ('SLOW' if d['Object']['Interval'] else 'FAST'))
                print 'system:\n'
                print '\tsystemmac: %s' % d['Object']['SystemIdMac']
                print '\tsysteprio: %s' % d['Object']['SystemPriority']
                print '\tsystemId: %s' % d['Object']['SystemId']
                print 'actor:'
                stateStr = '\tstate: '
                for s in ('Activity', 'Timeout', 'Aggregatable',
                          'Synchronization', 'Collecting', 'Distributing'):
                    if s == 'Synchronization' and not d['Object'][s]:
                        stateStr += s + ', '
                    elif s == 'Activity' and not d['Object'][s]:
                        stateStr += s + ', '
                    elif s in ('Activity', 'Synchronization'):
                        continue
                    elif d[s]:
                        stateStr += s + ', '
                print stateStr.rstrip(',')

                print '\tstats:'
                for s in ('LacpInPkts', 'LacpOutPkts', 'LacpRxErrors',
                          'LacpTxErrors', 'LacpUnknownErrors', 'LacpErrors',
                          'LampInPdu', 'LampOutPdu', 'LampInResponsePdu',
                          'LampOutResponsePdu'):
                    print '\t' + s, ': ', d['Object'][s]

                print 'partner:\n'
                print '\t' + 'key: %s' % d['Object']['PartnerKey']
                print '\t' + 'partnerid: ' + d['Object']['PartnerId']
                print 'debug:\n'
                try:
                    print '\t' + 'debugId: %s' % d['Object']['DebugId']
                    print '\t' + 'RxMachineState: %s' % RxMachineStateDict[
                        d['Object']['RxMachine']]
                    print '\t' + 'RxTime (rx pkt rcv): %s' % d['Object'][
                        'RxTime']
                    print '\t' + 'MuxMachineState: %s' % MuxMachineStateDict[
                        d['Object']['MuxMachine']]
                    print '\t' + 'MuxReason: %s' % d['Object']['MuxReason']
                    print '\t' + 'Actor Churn State: %s' % ChurnMachineStateDict[
                        d['Object']['ActorChurnMachine']]
                    print '\t' + 'Partner Churn State: %s' % ChurnMachineStateDict[
                        d['Object']['PartnerChurnMachine']]
                    print '\t' + 'Actor Churn Count: %s' % d['Object'][
                        'ActorChurnCount']
                    print '\t' + 'Partner Churn Count: %s' % d['Object'][
                        'PartnerChurnCount']
                    print '\t' + 'Actor Sync Transition Count: %s' % d[
                        'Object']['ActorSyncTransitionCount']
                    print '\t' + 'Partner Sync Transition Count: %s' % d[
                        'Object']['PartnerSyncTransitionCount']
                    print '\t' + 'Actor LAG ID change Count: %s' % d['Object'][
                        'ActorChangeCount']
                    print '\t' + 'Partner LAG ID change Count: %s' % d[
                        'Object']['PartnerChangeCount']
                except Exception as e:
                    print e

    def getLagGroups(self):
        lagGroup = self.swtch.getObjects('AggregationLacpStates')
        print '\n'
        if len(lagGroup) >= 0:
            print 'Name      Ifindex      LagType   Description      Enabled   MinLinks   Interval   Mode          SystemIdMac            SystemPriority    HASH'

            for d in lagGroup:
                print '%7s  %7s    %7s  %15s    %8s   %2s     %8s      %6s   %20s         %s              %s' % (
                    d['Object']['NameKey'], d['Object']['Ifindex'],
                    "LACP" if int(d['Object']['LagType']) == 0 else "STATIC",
                    d['Description'], "Enabled" if bool(d['Object']['Enabled'])
                    else "Disabled", d['Object']['MinLinks'],
                    "FAST" if int(d['Object']['Interval']) == 0 else "SLOW",
                    "ACTIVE" if int(d['Object']['LacpMode']) == 0 else
                    "PASSIVE", d['Object']['SystemIdMac'],
                    d['Object']['SystemPriority'], d['Object']['LagHash'])
コード例 #14
0
ファイル: snap_commands.py プロジェクト: ashutoshshanker/apps
 def __init__(self,switch_ip):
 		self.switch_ip=switch_ip
 		self.swtch = FlexSwitch(self.switch_ip,8080)
コード例 #15
0
ファイル: getPorts.py プロジェクト: zirben0/flexSdk
import sys
import os
import simplejson as json
sys.path.append(os.path.abspath('../../py'))
from flexswitchV2 import FlexSwitch

"""This program demonstrates 
   simple read APIs supported by FlexSwitch SDK. 
   This specific example is reading all the Port states.
   getAllPortStates returns a list of ports. Each item in the
   list of ports would contain port attributes. """
   

if __name__ == '__main__':
    swtch = FlexSwitch ('10.1.10.240', 8080)  # Instantiate object to talk to flexSwitch
    ports = swtch.getAllPortStates()          # Get all the state information for all ports
    port = ports[0]      #Just print first port information
    print json.dumps(port['Object'])



コード例 #16
0
 def get_portstats(self, stwitch_ip):
     swtch = FlexSwitch(stwitch_ip,
                        8080)  # Instantiate object to talk to flexSwitch
     ports = swtch.getAllPortStates()
     return ports
コード例 #17
0
 def get_BGPstats(self, stwitch_ip):
     swtch = FlexSwitch(stwitch_ip,
                        8080)  # Instantiate object to talk to flexSwitch
     bgps = swtch.getAllBGPv4NeighborStates()
     return bgps