def GetTNStatus(auth_list): SessionNSX = ConnectNSX(auth_list) hostnode_json = GetAPI( SessionNSX[0], '/api/v1/search/query?query=resource_type:Hostnode', auth_list) hostnodes = (hostnode_json["result_count"]) print( "\n========================================================================================================" ) for n in range(hostnodes): print('') print('Host Node: ' + style.ORANGE + hostnode_json["results"][n]["display_name"] + style.NORMAL) if hostnode_json["results"][n]["status"][ "lcp_connectivity_status"] == 'UP': print('LCP Connectivity Status: ' + style.GREEN + hostnode_json["results"][n]["status"] ["lcp_connectivity_status"] + style.NORMAL) else: print('LCP Connectivity Status: ' + style.RED + hostnode_json["results"][n]["status"] ["lcp_connectivity_status"] + style.NORMAL) if hostnode_json["results"][n]["status"][ "mpa_connectivity_status"] == 'UP': print('MPA Connectivity Status: ' + style.GREEN + hostnode_json["results"][n]["status"] ["mpa_connectivity_status"] + style.NORMAL) else: print('MPA Connectivity Status: ' + style.RED + hostnode_json["results"][n]["status"] ["mpa_connectivity_status"] + style.NORMAL) print('MPA Connectivity Status Details: ' + style.ORANGE + hostnode_json["results"][n]["status"] ["mpa_connectivity_status_details"] + style.NORMAL) if 'INSTALL_SUCCESSFUL' in hostnode_json["results"][n]["status"][ "host_node_deployment_status"]: print('Host Node Deployment Status: ' + style.GREEN + hostnode_json["results"][n]["status"] ["host_node_deployment_status"] + style.NORMAL) else: print('Host Node Deployment Status: ' + style.RED + hostnode_json["results"][n]["status"] ["host_node_deployment_status"] + style.NORMAL) try: print('NSX Controller IP: ' + style.ORANGE + hostnode_json["results"][n]["status"] ["lcp_connectivity_status_details"][0]["control_node_ip"] + style.NORMAL) print('NSX Controller Status: ' + style.GREEN + hostnode_json["results"][n]["status"] ["lcp_connectivity_status_details"][0]["status"] + style.NORMAL) print('') except: print('NSX Controller IP: ' + style.RED + 'UNKNOWN' + style.NORMAL) print('NSX Controller Status: ' + style.RED + 'UNKNOWN' + style.NORMAL) print('') print( "========================================================================================================" )
def SheetT1ForwardingTable(auth_list, WORKBOOK, TN_WS, NSX_Config={}): NSX_Config['T1ForwardingTable'] = [] Dict_T1 = {} # Connect NSX SessionNSX = ConnectNSX(auth_list) ########### GET Edge Clusters ########### #edge_list_url = '/api/v1/search/query?query=resource_type:Edgenode' #edge_list_json = GetAPI(SessionNSX[0],edge_list_url, auth_list) ########### GET Tier-1 Gateways ########### t1_url = '/policy/api/v1/infra/tier-1s' t1_json = GetAPI(SessionNSX[0], t1_url, auth_list) ########### CREATE LIST OF TUPLES - EDGE-ID / EDGE NAME ########### #edge_list = [] #if edge_list_json["result_count"] > 0: # for edge in edge_list_json["results"]: # edge_list.append(tuple((edge['id'],edge['display_name']))) t1_id_list = [] XLS_Lines = [] TN_HEADER_ROW = ('T1 Router', 'Edge Node Path', 'Edge ID', 'HA Status', 'Route Type', 'Network', 'Admin Distance', 'Next Hop', 'LR Component ID', 'LR Component Type') if t1_json["result_count"] > 0: for T1 in t1_json["results"]: t1_id_list.append(T1['display_name']) for T1 in t1_id_list: forwardingURL = t1_url + '/' + str(T1) + '/forwarding-table' # Get T1 State t1_state_json = GetAPI(SessionNSX[0], t1_url + '/' + str(T1) + '/state', auth_list) nb_routes = 0 if isinstance(t1_state_json, dict) and 'tier1_status' in t1_state_json: if 'per_node_status' in t1_state_json['tier1_status']: for node in t1_state_json['tier1_status'][ 'per_node_status']: if node['high_availability_status'] != 'STANDBY': EdgeID = node['transport_node_id'] HAStatus = node['high_availability_status'] forwardingURL = t1_url + '/' + str( T1) + '/forwarding-table?edge_id=' + EdgeID # Get T1 forwardoing table t1_routingtable_json = GetAPI(SessionNSX[0], forwardingURL, auth_list) if isinstance( t1_routingtable_json, dict ) and 'results' in t1_routingtable_json and t1_routingtable_json[ 'result_count'] > 0: for n in t1_routingtable_json["results"]: # Get routes nb_routes = len(n['route_entries']) for entry in n['route_entries']: Dict_T1['edge_name'] = n['edge_node'] Dict_T1['edge_id'] = EdgeID Dict_T1['ha'] = HAStatus Dict_T1['T0_name'] = T1 Dict_T1['route_type'] = entry['route_type'] Dict_T1['network'] = entry['network'] Dict_T1['ad'] = entry['admin_distance'] Dict_T1['next_hop'] = entry['next_hop'] Dict_T1['lr_id'] = entry['lr_component_id'] Dict_T1['lr_type'] = entry['lr_component_type'] NSX_Config['T1ForwardingTable'].append(Dict_T1) XLS_Lines.append([ T1, n['edge_node'], EdgeID, HAStatus, entry['route_type'], entry['network'], entry['admin_distance'], entry['next_hop'], entry['lr_component_id'], entry['lr_component_type'] ]) elif not t1_routingtable_json: XLS_Lines.append([ T1, "No Forwarding table found", "", "", "", "", "", "", "", "" ]) else: XLS_Lines.append([ T1, "T1 not deployed on Edge Cluster. DR Only", "", "", "", "", "", "", "", "" ]) print(" --> Get forwarding tables of " + style.ORANGE + T1 + style.NORMAL + " Router: " + style.ORANGE + str(nb_routes) + style.NORMAL + " route(s)") else: XLS_Lines.append( ["No Forwarding table found", "", "", "", "", "", "", "", "", ""]) FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
def GetNSXSummary(auth_list): SessionNSX = ConnectNSX(auth_list) t0_gateway_url = '/policy/api/v1/infra/tier-0s' t1_gateway_url = '/policy/api/v1/infra/tier-1s' segment_url = '/policy/api/v1/infra/segments' groups_url = '/policy/api/v1/infra/domains/default/groups' ctx_profiles_url = '/policy/api/v1/infra/context-profiles' services_url = '/policy/api/v1/infra/services' deployed_mgmt_nodes_url = '/api/v1/cluster' online_mgmt_nodes_url = '/api/v1/cluster/status' edge_clstr_url = '/api/v1/edge-clusters' edge_tn_url = '/api/v1/search/query?query=resource_type:Edgenode' host_tn_url = '/api/v1/search/query?query=resource_type:Hostnode' deployed_json = GetAPI(SessionNSX[0], deployed_mgmt_nodes_url, auth_list) deployed = len(deployed_json["nodes"]) online_nodes_json = GetAPI(SessionNSX[0], online_mgmt_nodes_url, auth_list) online_nodes = len( online_nodes_json['mgmt_cluster_status']['online_nodes']) edge_clstr_json = GetAPI(SessionNSX[0], edge_clstr_url, auth_list) edge_tn_json = GetAPI(SessionNSX[0], edge_tn_url, auth_list) host_tn_json = GetAPI(SessionNSX[0], host_tn_url, auth_list) t0_gateway_json = GetAPI(SessionNSX[0], t0_gateway_url, auth_list) t1_gateway_json = GetAPI(SessionNSX[0], t1_gateway_url, auth_list) segment_json = GetAPI(SessionNSX[0], segment_url, auth_list) groups_json = GetAPI(SessionNSX[0], groups_url, auth_list) ctx_profiles_json = GetAPI(SessionNSX[0], ctx_profiles_url, auth_list) services_json = GetAPI(SessionNSX[0], services_url, auth_list) YAML_DICT = ReadYAMLCfgFile(YAML_CFG_FILE) #Display Summary Output print('\nNSX Manager Summary for: https://' + style.ORANGE + YAML_DICT['NSX_MGR_IP'] + style.NORMAL) print('\nDeployed NSX Manager Nodes:\t' + style.ORANGE + str(deployed) + style.NORMAL) print('Online NSX Manager Nodes:\t' + style.ORANGE + str(online_nodes) + style.NORMAL) print('\nEdge Clusters:\t\t' + style.ORANGE + str(edge_clstr_json["result_count"]) + style.NORMAL) print('Edge Transport Nodes:\t' + style.ORANGE + str(edge_tn_json["result_count"]) + style.NORMAL) print('Host Transport Nodes:\t' + style.ORANGE + str(host_tn_json["result_count"]) + style.NORMAL) print('\nT0 Gateways:\t' + style.ORANGE + str(t0_gateway_json["result_count"]) + style.NORMAL) print('T1 Gateways:\t' + style.ORANGE + str(t1_gateway_json["result_count"]) + style.NORMAL) print('Segments:\t' + style.ORANGE + str(segment_json["result_count"]) + style.NORMAL) print('\nNS Groups:\t\t' + style.ORANGE + str(groups_json["result_count"]) + style.NORMAL) print('Context Profiles:\t' + style.ORANGE + str(ctx_profiles_json["result_count"]) + style.NORMAL) print('Services:\t\t' + style.ORANGE + str(services_json["result_count"]) + style.NORMAL)
def GetBGPSessions(auth_list): SessionNSX = ConnectNSX(auth_list) t0_url = '/policy/api/v1/infra/tier-0s' t0_json = GetAPI(SessionNSX[0], t0_url, auth_list) print( "\n========================================================================================================" ) print( '\n----------------------------------- NSX BGP Sessions ---------------------------------------------' ) print( '| Source IP address | Neighbor IP Address | Remote AS | In Prefixes | Out Prefixes | Status' ) print( '--------------------------------------------------------------------------------------------------' ) tab = [] if isinstance( t0_json, dict) and 'results' in t0_json and t0_json['result_count'] > 0: for t0 in t0_json["results"]: t0_localeservice_url = "/policy/api/v1/infra/tier-0s/" + t0[ 'display_name'] + "/locale-services/" t0_localeservices_json = GetAPI(SessionNSX[0], t0_localeservice_url, auth_list) for t0_localeservice in t0_localeservices_json['results']: bgpstatus_url = "/policy/api/v1/infra/tier-0s/" + t0[ 'display_name'] + "/locale-services/" + t0_localeservice[ 'id'] + "/bgp/neighbors/status" bgpstatus_json = GetAPI(SessionNSX[0], bgpstatus_url, auth_list) # BGP Sessions treatment if isinstance(bgpstatus_json, dict) and 'results' in bgpstatus_json: for session in bgpstatus_json['results']: tab.append([ session['source_address'], session['neighbor_address'], session['remote_as_number'], session['total_in_prefix_count'], session['total_out_prefix_count'], session['connection_state'] ]) else: tab.append(['no BGP sessions']) else: tab.append(['no BGP sessions']) for i in tab: if len(i) > 1: print( '{:<20s} {:<23s} {:<11s} {:^11d} {:^17d}\x1b[0;31;40m{:<13s}\x1b[0m' .format(i[0], i[1], i[2], i[3], i[4], i[5])) print( '--------------------------------------------------------------------------------------------------' ) print( "\n========================================================================================================" )
def SheetT0RoutingTable(auth_list, WORKBOOK, TN_WS, NSX_Config={}): NSX_Config['T0RoutingTable'] = [] Dict_T0 = {} SessionNSX = ConnectNSX(auth_list) ########### GET Tier-0 Gateways ########### t0_url = '/policy/api/v1/infra/tier-0s' t0_json = GetAPI(SessionNSX[0], t0_url, auth_list) t0_id_list = [] for i in t0_json["results"]: t0_id_list.append(i['display_name']) XLS_Lines = [] TN_HEADER_ROW = ('T0', 'Edge Node Path', 'Route Type', 'Network', 'Admin Distance', 'Next Hop', 'LR Component ID', 'LR Component Type') for T0 in t0_id_list: nb_routes = 0 t0_routingtable_json = GetAPI( SessionNSX[0], t0_url + '/' + str(T0) + '/routing-table', auth_list) if isinstance( t0_routingtable_json, dict ) and 'results' in t0_routingtable_json and t0_routingtable_json[ 'result_count'] > 0: for n in t0_routingtable_json["results"]: nb_routes = len(n["route_entries"]) # get routes for entry in n['route_entries']: Dict_T0['edge'] = n['edge_node'] Dict_T0['T0_name'] = T0 Dict_T0['route_type'] = entry['route_type'] Dict_T0['network'] = entry['network'] Dict_T0['ad'] = entry['admin_distance'] Dict_T0['next_hop'] = entry['next_hop'] Dict_T0['lr_id'] = entry['lr_component_id'] Dict_T0['lr_type'] = entry['lr_component_type'] NSX_Config['T0RoutingTable'].append(Dict_T0) XLS_Lines.append([ T0, n['edge_node'], entry['route_type'], entry['network'], entry['admin_distance'], entry['next_hop'], entry['lr_component_id'], entry['lr_component_type'] ]) elif not t0_routingtable_json: XLS_Lines.append( [T0, "No Routing table found", "", "", "", "", "", ""]) else: XLS_Lines.append([ T0, " T1 not deployed on Edge Cluster. DR Only", "", "", "", "", "", "" ]) print(" --> Get forwarding tables of " + style.ORANGE + T0 + style.NORMAL + " Router: " + style.ORANGE + str(nb_routes) + style.NORMAL + " route(s)") if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV, TN_HEADER_ROW, XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
def SheetAlarms(auth_list, WORKBOOK, TN_WS, NSX_Config={}): Dict_Alarm = {} # Dict alarm initialization NSX_Config['Alarms'] = [] # Connect NSX SessionNSX = ConnectNSX(auth_list) TN_json = GetAPI(SessionNSX[0], '/api/v1/transport-nodes', auth_list) Edge_json = GetAPI(SessionNSX[0], '/api/v1/cluster/nodes', auth_list) alarms_url = '/api/v1/alarms' alarms_json = GetAPI(SessionNSX[0], alarms_url, auth_list) nb = alarms_json['result_count'] node_dict = {} # Construct Dicts of Edge Node and Transport Node for Name from ID if TN_json['result_count'] > 0: for TN in TN_json['results']: node_dict.update({TN["id"]: TN["display_name"]}) if Edge_json['result_count'] > 0: for EDGE in Edge_json['results']: node_dict.update({EDGE["id"]: EDGE["display_name"]}) NodeName = "" XLS_Lines = [] TN_HEADER_ROW = ('Feature', 'Event Type', 'Reporting Node', 'Node Ressource Type', 'Entity Name', 'Severity', 'Last Reported Time', 'Status', 'Description', 'Recommended Action') if isinstance( alarms_json, dict ) and 'results' in alarms_json and alarms_json['result_count'] > 0: for alarm in alarms_json['results']: # Get Name of Node from ID for key, value in node_dict.items(): if key == alarm['entity_id']: NodeName = value # Transform date and time of alarms dtt = datetime.datetime.fromtimestamp( float(alarm['last_reported_time'] / 1000)).strftime('%Y-%m-%d %H:%M:%S') # Create line XLS_Lines.append([ alarm['feature_name'], alarm['event_type'], NodeName, alarm['node_resource_type'], alarm['entity_id'], alarm['severity'], dtt, alarm['status'], alarm['description'], alarm['recommended_action'] ]) # Fill alarm Dict Dict_Alarm['feature_name'] = alarm['feature_name'] Dict_Alarm['event_type'] = alarm['event_type'] Dict_Alarm['node_name'] = NodeName Dict_Alarm['node_resource_type'] = alarm['node_resource_type'] Dict_Alarm['entity_id'] = alarm['entity_id'] Dict_Alarm['severity'] = alarm['severity'] Dict_Alarm['time'] = dtt Dict_Alarm['status'] = alarm['status'] Dict_Alarm['description'] = alarm['description'] Dict_Alarm['recommended_action'] = alarm['recommended_action'] NSX_Config['Alarms'].append(Dict_Alarm) else: XLS_Lines.append(['No results', "", "", "", "", "", "", "", "", ""]) # Create sheet if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV, TN_HEADER_ROW, XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA") ConditionnalFormat(TN_WS, 'F', 'CRITICAL', True, 'RED') ConditionnalFormat(TN_WS, 'F', 'HIGH', True, 'ORANGE') ConditionnalFormat(TN_WS, 'H', 'RESOLVED', True, 'GREEN')
def SheetRouterSum(auth_list,WORKBOOK,TN_WS, NSX_Config = {}): if 'LR' not in NSX_Config: NSX_Config['LR'] = [] Dict_LR = {} SessionNSX = ConnectNSX(auth_list) ########### GET Logical Routers ########### lr_list_url = '/api/v1/logical-routers' lr_list_json = GetAPI(SessionNSX[0],lr_list_url, auth_list) ########### GET Edge Clusters ########### edge_list_url = '/api/v1/edge-clusters' edge_list_json = GetAPI(SessionNSX[0],edge_list_url, auth_list) ########### CREATE LIST OF TUPLES - EDGE-ID / EDGE NAME ########### edge_list = [] if edge_list_json['result_count'] > 0: for i in edge_list_json["results"]: edge_list.append(tuple((i['id'],i['display_name']))) XLS_Lines = [] TN_HEADER_ROW = ('Logical Router Name', 'Logical Router ID', 'Edge Cluster Name', 'Edge Custer ID', 'Logical Router Type', 'High Availability Mode', 'Enable Standby Relocation', 'Failover Mode') if lr_list_json['result_count'] > 0: for LR in lr_list_json['results']: HA = "" RELOC = "" FAILOVER = "" LRType = "" EdgeClusterName = "" LRID = "" if 'edge_cluster_id' in LR: LRID = LR['edge_cluster_id'] # Get Edge Cluster Name for ec in edge_list: if LR['edge_cluster_id'] == ec[0]: EdgeClusterName = ec[1] if 'router_type' in LR: LRType = LR['router_type'] if 'high_availability_mode' in LR: HA = LR['high_availability_mode'] if 'allocation_profile' in LR: RELOC = LR['allocation_profile']['enable_standby_relocation'] if 'failover_mode' in LR: FAILOVER = LR['failover_mode'] Dict_LR['name'] = LR['display_name'] Dict_LR['id'] = LR['id'] Dict_LR['edge_cluster_name'] = EdgeClusterName Dict_LR['edge_cluster_id'] = LRID Dict_LR['router_type'] = LRType Dict_LR['failover_mode'] = FAILOVER Dict_LR['ha_mode'] = HA Dict_LR['relocation'] = RELOC NSX_Config['LR'].append(Dict_LR) XLS_Lines.append([LR['display_name'], LR['id'],EdgeClusterName, LRID, LRType, HA, RELOC, FAILOVER]) else: XLS_Lines.append(['No results', "", "", "", "", "", "", ""]) if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV,TN_HEADER_ROW,XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK,TN_WS.title,TN_HEADER_ROW,XLS_Lines,"0072BA")
def SheetSecGrp(auth_list, WORKBOOK, TN_WS, NSX_Config={}): NSX_Config['Groups'] = [] Dict_Groups = {} domain_id = 'default' # Connection for get Groups criteria - REST/API Groups_list_url = '/policy/api/v1/infra/domains/' + domain_id + '/groups' SessionNSX = ConnectNSX(auth_list) Groups_list_json = GetAPI(SessionNSX[0], Groups_list_url, auth_list) XLS_Lines = [] TN_HEADER_ROW = ('Group Name', 'Tags', 'Scope', 'Criteria Type', 'Criteria', 'IP addresses', 'Virtual Machines', 'Segments', 'Segments Ports') if isinstance(Groups_list_json, dict) and 'results' in Groups_list_json and Groups_list_json[ 'result_count'] > 0: count = 1 for group in Groups_list_json['results']: print( str(count) + " - Treating NS group: " + style.ORANGE + group['display_name'] + style.NORMAL) count += 1 # Get Tag and scope List_Tag = [] List_Scope = [] # Check if tag is in a group if "tags" in group: for tag in group['tags']: List_Tag.append(tag['tag']) List_Scope.append(tag['scope']) Tags = ','.join(List_Tag) Scope = ','.join(List_Scope) else: Tags = "" Scope = "" #Criteria Treatment if group['expression'] == []: print('skipping group without expression') continue for nbcriteria in group['expression']: criteria = GetCriteria(SessionNSX[0], auth_list, nbcriteria) # Create IP Address List for each group IPs_url = '/policy/api/v1/infra/domains/' + domain_id + '/groups/' + group[ 'id'] + '/members/ip-addresses' IPs_json = GetAPI(SessionNSX[0], IPs_url, auth_list) IP = "" if isinstance( IPs_json, dict ) and 'results' in IPs_json and 'result_count' in IPs_json and IPs_json[ 'result_count'] > 0: IP = ', '.join(IPs_json['results']) # Create Virtual Machine List for each group VMs_url = '/policy/api/v1/infra/domains/' + domain_id + '/groups/' + group[ 'id'] + '/members/virtual-machines' VMs_json = GetAPI(SessionNSX[0], VMs_url, auth_list) VM = "" VMList = [] if isinstance( VMs_json, dict ) and 'results' in VMs_json and 'result_count' in VMs_json and VMs_json[ 'result_count'] > 0: for vm in VMs_json['results']: VMList.append(vm['display_name']) VM = ', '.join(VMList) # Create Segment List for each group Segs_url = '/policy/api/v1/infra/domains/' + domain_id + '/groups/' + group[ 'id'] + '/members/segments' Segs_json = GetAPI(SessionNSX[0], Segs_url, auth_list) Segment = "" SegList = [] if isinstance( Segs_json, dict ) and 'results' in Segs_json and 'result_count' in Segs_json and Segs_json[ 'result_count'] > 0: for seg in Segs_json['results']: SegList.append(seg['display_name']) Segment = ', '.join(SegList) # Create Segment Port/vNIC List for each group Seg_Ports_url = '/policy/api/v1/infra/domains/' + domain_id + '/groups/' + group[ 'id'] + '/members/segment-ports' Seg_Ports_json = GetAPI(SessionNSX[0], Seg_Ports_url, auth_list) SegPort = "" SegPortList = [] if isinstance( Seg_Ports_json, dict ) and 'results' in Seg_Ports_json and 'result_count' in Seg_Ports_json and Seg_Ports_json[ 'result_count'] > 0: for segport in Seg_Ports_json['results']: SegPortList.append(segport['display_name']) SegPort = ', '.join(SegPortList) Dict_Groups['name'] = group['display_name'] Dict_Groups['tags'] = List_Tag Dict_Groups['scope'] = List_Scope Dict_Groups['type_crtieria'] = criteria[1] Dict_Groups['criteria'] = criteria[0] Dict_Groups['ip'] = IP Dict_Groups['vm'] = VMList Dict_Groups['segment'] = SegList Dict_Groups['segment_port'] = SegPortList NSX_Config['Groups'].append(Dict_Groups) XLS_Lines.append([ group['display_name'], Tags, Scope, '\n'.join(criteria[1]), criteria[0], IP, VM, Segment, SegPort ]) else: XLS_Lines.append(['No results', "", "", "", "", "", "", "", ""]) if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV, TN_HEADER_ROW, XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
def SheetBGPSession(auth_list, WORKBOOK, TN_WS, NSX_Config={}): NSX_Config['T0Sessions'] = [] Dict_Sessions = {} SessionNSX = ConnectNSX(auth_list) ########### GET Tier-0 Gateways ########### t0_url = '/policy/api/v1/infra/tier-0s' t0_json = GetAPI(SessionNSX[0], t0_url, auth_list) XLS_Lines = [] TN_HEADER_ROW = ('T0', 'BGP status', 'ECMP', 'Inter-SR', 'Source IP address', 'Local AS', 'Neighbor IP address', 'Remote AS', 'Total IN Prefixes', 'Total OUT prefixes', 'Session Status') if isinstance( t0_json, dict) and 'results' in t0_json and t0_json['result_count'] > 0: for t0 in t0_json["results"]: #localservice_url = "/policy/api/v1/infra/tier-0s/"+ t0['display_name'] +"/locale-services" localservice = "default" bgpstatus_url = "/policy/api/v1/infra/tier-0s/" + t0[ 'display_name'] + "/locale-services/" + localservice + "/bgp/neighbors/status" bgpconfig_url = "/policy/api/v1/infra/tier-0s/" + t0[ 'display_name'] + "/locale-services/" + localservice + "/bgp" #t0_localservice = GetAPI(SessionNSX[0],localservice_url, auth_list) bgpstatus_json = GetAPI(SessionNSX[0], bgpstatus_url, auth_list) bgpconfig_json = GetAPI(SessionNSX[0], bgpconfig_url, auth_list) Dict_Sessions['T0_name'] = t0['display_name'] # BGP Sessions treatment if isinstance(bgpstatus_json, dict) and 'results' in bgpstatus_json: Dict_Sessions['bgp_sessions'] = [] Dict_bgp_session = {} if 'local_as_num' in bgpconfig_json: Dict_bgp_session['local_as'] = str( bgpconfig_json['local_as_num']) else: Dict_bgp_session['local_as'] = "" if 'inter_sr_ibgp' in bgpconfig_json: Dict_bgp_session['inter_sr_ibgp'] = str( bgpconfig_json['inter_sr_ibgp']).upper() else: Dict_bgp_session['inter_sr_ibgp'] = '' Dict_bgp_session['bgp_status'] = str( bgpconfig_json['enabled']).upper() Dict_bgp_session['ecmp'] = str(bgpconfig_json['ecmp']).upper() for session in bgpstatus_json['results']: Dict_bgp_session['source_ip'] = session['source_address'] Dict_bgp_session['remote_ip'] = session['neighbor_address'] Dict_bgp_session['remote_as'] = str( session['remote_as_number']) Dict_bgp_session['total_in'] = str( session['total_in_prefix_count']) Dict_bgp_session['total_out'] = str( session['total_out_prefix_count']) Dict_bgp_session['connection_state'] = session[ 'connection_state'] Dict_Sessions['bgp_sessions'].append(Dict_bgp_session) XLS_Lines.append([ Dict_Sessions['T0_name'], Dict_bgp_session['bgp_status'], Dict_bgp_session['ecmp'], Dict_bgp_session['inter_sr_ibgp'], Dict_bgp_session['source_ip'], Dict_bgp_session['local_as'], Dict_bgp_session['remote_ip'], Dict_bgp_session['remote_as'], Dict_bgp_session['total_in'], Dict_bgp_session['total_out'], Dict_bgp_session['connection_state'] ]) elif not bgpstatus_json: XLS_Lines.append([ t0['display_name'], "No BGP sessions", "", "", "", "", "", "", "", "", "" ]) else: XLS_Lines.append([ t0['display_name'], " No BGP sessions", "", "", "", "", "", "", "", "", "" ]) NSX_Config['T0Sessions'].append(Dict_Sessions) print(" --> Get BGP sessions for " + style.ORANGE + t0['display_name'] + style.NORMAL) else: XLS_Lines.append( ["No T0 router found", "", "", "", "", "", "", "", "", "", ""]) FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA") ConditionnalFormat(TN_WS, 'K2:K' + str(len(XLS_Lines) + 1), 'ESTABLISHED') ConditionnalFormat(TN_WS, 'B2:B' + str(len(XLS_Lines) + 1), 'TRUE')
def GetDFWRulesStats(auth_list): # Get domain id SessionNSX = ConnectNSX(auth_list) domains_url = '/policy/api/v1/infra/domains' domains_json = GetAPI(SessionNSX[0], domains_url, auth_list) domain_name = 'default' if isinstance( domains_json, dict ) and 'results' in domains_json and domains_json['result_count'] > 0: domain_name = domains_json['results'][0]['id'] # Get all DFW policies dfw_url = '/policy/api/v1/infra/domains/default/security-policies' dfw_json = GetAPI(SessionNSX[0], dfw_url, auth_list) if isinstance( dfw_json, dict) and 'results' in dfw_json and dfw_json['result_count'] > 0: print( "\n====================================================================================" ) print( '\n------------------------------- DFW Rules Stats ------------------------------------' ) print( '| Rule Name | Rule Unique ID | Hit Count | Packet Count | Byte Count |' ) print( '--------------------------------------------------------------------------------------' ) for policy in dfw_json['results']: policy_name = policy['display_name'] policy_id = policy['id'] if (policy['category'] == "Ethernet"): continue print('--- Policy: ' + policy_name + ' (id: ' + policy_id + ')') # Create Dict Rules Name & ID rules_url = '/policy/api/v1/infra/domains/default/security-policies' + '/' + policy_id + '/rules' rules_json = GetAPI(SessionNSX[0], rules_url, auth_list) rule_dict = {} if isinstance( rules_json, dict ) and 'results' in rules_json and rules_json['result_count'] > 0: for rule in rules_json['results']: rule_dict[str(rule['rule_id'])] = rule['display_name'] # For the current policies, Get Statistics for all rules rules_stats_url = '/policy/api/v1/infra/domains/default/security-policies' + "/" + policy_id + "/statistics" rules_stats_url_json = GetAPI(SessionNSX[0], rules_stats_url, auth_list) if isinstance( rules_stats_url_json, dict ) and 'results' in rules_stats_url_json and rules_stats_url_json[ 'result_count'] > 0: for stat_res in rules_stats_url_json['results']: item = stat_res['statistics']['results'] for rule_stat in item: rule_unique_id = rule_stat['internal_rule_id'] hit_count = rule_stat['hit_count'] packet_count = rule_stat['packet_count'] byte_count = rule_stat['byte_count'] print(' {:<18} {:<16} {:^12} {:^15} {:^12}'.format( '{:19.19}'.format(rule_dict[str(rule_unique_id)]), rule_unique_id, hit_count, packet_count, str(byte_count) + 'B')) print( '--------------------------------------------------------------------------------------' ) print( "======================================================================================" )
def SheetRouterPorts(auth_list, WORKBOOK, TN_WS, NSX_Config={}): if 'LRPorts' not in NSX_Config: NSX_Config['LRPorts'] = [] Dict_Ports = {} SessionNSX = ConnectNSX(auth_list) ########### GET LogicalPortDownLink ########### LRports_Down_url = '/api/v1/search/query?query=resource_type:LogicalRouterDownLinkPort' LRports_Down_json = GetAPI(SessionNSX[0], LRports_Down_url, auth_list) ########### GET Logical Routers ########### lr_ports_url = '/api/v1/search/query?query=resource_type:LogicalPort' lr_ports_json = GetAPI(SessionNSX[0], lr_ports_url, auth_list) ########### GET Logical Routers ########### lr_list_url = '/api/v1/logical-routers' lr_list_json = GetAPI(SessionNSX[0], lr_list_url, auth_list) ########### CREATE LIST OF TUPLES - EDGE-ID / EDGE NAME ########### lswitch_list = [] XLS_Lines = [] TN_HEADER_ROW = ('LR Port Name', 'ID', 'Attachment Type', 'Logical Router Name', 'Attachment ID', 'Logical Switch ID', 'Logical Switch', 'Create User', 'Admin State', 'Status') ########### GET Logical-Switches ########### lswitch_url = '/api/v1/logical-switches' lswitch_json = GetAPI(SessionNSX[0], lswitch_url, auth_list) for i in lswitch_json["results"]: lswitch_list.append(tuple((i['id'], i['display_name']))) if lr_ports_json['result_count'] > 0: for port in lr_ports_json["results"]: # Check is attachment key is in Dict if 'attachment' in port: Attachement_type = port['attachment']['attachment_type'] Attachement_ID = port['attachment']['id'] else: Attachement_type = 'No Attachment' Attachement_ID = 'No Attachment' # Get the name of LS LS_Name = "" LR_Name = "" for ls in lswitch_list: if port['logical_switch_id'] == ls[0]: LS_Name = ls[1] # Get Router Name for lr in LRports_Down_json['results']: if 'linked_logical_switch_port_id' in lr: if port['id'] == lr[ 'linked_logical_switch_port_id'][ 'target_id']: for router in lr_list_json['results']: if lr['logical_router_id'] == router['id']: LR_Name = router['display_name'] Dict_Ports['name'] = port['display_name'] Dict_Ports['state'] = port['admin_state'] Dict_Ports['create_user'] = port['_create_user'] Dict_Ports['router'] = LR_Name Dict_Ports['id'] = port['id'] Dict_Ports['att_type'] = Attachement_type Dict_Ports['att_id'] = Attachement_ID Dict_Ports['LS_id'] = port['logical_switch_id'] Dict_Ports['LS_name'] = LS_Name Dict_Ports['status'] = port['status']['status'] NSX_Config['LRPorts'].append(Dict_Ports) XLS_Lines.append([ port['display_name'], port['id'], Attachement_type, LR_Name, Attachement_ID, port['logical_switch_id'], LS_Name, port['_create_user'], port['admin_state'], port['status']['status'] ]) else: XLS_Lines.append(['No results', "", "", "", "", "", "", "", ""]) if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV, TN_HEADER_ROW, XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA") if len(XLS_Lines) > 0: ConditionnalFormat(TN_WS, 'J2:J' + str(len(XLS_Lines) + 1), 'UP') ConditionnalFormat(TN_WS, 'I2:I' + str(len(XLS_Lines) + 1), 'UP')
def SheetFabDiscoveredNodes(auth_list, WORKBOOK, TN_WS, NSX_Config={}): Dict_DiscoveredNodes = {} # Dict Discovered nodes initialization NSX_Config['DiscoveredNodes'] = [] # Connect to NSX SessionNSX = ConnectNSX(auth_list) discovered_nodes_url = '/api/v1/fabric/discovered-nodes' discovered_nodes_json = GetAPI(SessionNSX[0], discovered_nodes_url, auth_list) # Construct Line TN_HEADER_ROW = ('Display name', 'OS Type', 'OS Version', 'Node Type', 'Hostname', 'Full Name', 'Management IP', 'Domain name', 'DNS', 'UUID', 'Powerstate', 'In Maintenance Mode', 'Build', 'Vendor', 'Model', 'Serial Number', 'Connection State', 'Licensed Product Name', 'Licensed Product Version', 'Mgmt Server IP', 'Lockdown Mode', 'DAS Host State') XLS_Lines = [] # Check if Discovered Nodes present if isinstance( discovered_nodes_json, dict ) and 'results' in discovered_nodes_json and discovered_nodes_json[ 'result_count'] > 0: for node in discovered_nodes_json['results']: Dict_Properties = {} # Loop in properties for propertie in node['origin_properties']: if propertie['key'] == 'hostName': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'fullName': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'managementIp': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'domainName': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'dnsConfigAddress': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'uuid': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'powerState': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'inMaintenanceMode': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'build': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'vendor': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'model': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'serialNumber': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'connectionState': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'licenseProductName': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'licenseProductVersion': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'managementServerIp': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'lockdownMode': Dict_Properties[propertie['key']] = propertie['value'] if propertie['key'] == 'dasHostState': Dict_Properties[propertie['key']] = propertie['value'] # Fill Discovered Nodes Dict Dict_DiscoveredNodes['node_name'] = node['display_name'] Dict_DiscoveredNodes['event_type'] = node['os_type'] Dict_DiscoveredNodes['node_name'] = node['os_version'] Dict_DiscoveredNodes['node_resource_type'] = node['node_type'] Dict_DiscoveredNodes['hostName'] = Dict_Properties['hostName'] Dict_DiscoveredNodes['fullName'] = Dict_Properties['fullName'] Dict_DiscoveredNodes['managementIp'] = Dict_Properties[ 'managementIp'] try: Dict_DiscoveredNodes['domainName'] = Dict_Properties[ 'domainName'] except: Dict_Properties['domainName'] = 'No Domain Name' Dict_DiscoveredNodes['dnsConfigAddress'] = Dict_Properties[ 'dnsConfigAddress'] Dict_DiscoveredNodes['uuid'] = Dict_Properties['uuid'] Dict_DiscoveredNodes['powerState'] = Dict_Properties['powerState'] Dict_DiscoveredNodes['inMaintenanceMode'] = Dict_Properties[ 'inMaintenanceMode'] Dict_DiscoveredNodes['build'] = Dict_Properties['build'] Dict_DiscoveredNodes['vendor'] = Dict_Properties['vendor'] Dict_DiscoveredNodes['model'] = Dict_Properties['model'] Dict_DiscoveredNodes['serialNumber'] = Dict_Properties[ 'serialNumber'] Dict_DiscoveredNodes['connectionState'] = Dict_Properties[ 'connectionState'] Dict_DiscoveredNodes['licenseProductName'] = Dict_Properties[ 'licenseProductName'] Dict_DiscoveredNodes['licenseProductVersion'] = Dict_Properties[ 'licenseProductVersion'] Dict_DiscoveredNodes['managementServerIp'] = Dict_Properties[ 'managementServerIp'] Dict_DiscoveredNodes['lockdownMode'] = Dict_Properties[ 'lockdownMode'] Dict_DiscoveredNodes['dasHostState'] = Dict_Properties[ 'dasHostState'] NSX_Config['DiscoveredNodes'].append(Dict_DiscoveredNodes) # write one line for a node XLS_Lines.append([ node['display_name'], node['os_type'], node['os_version'], node['node_type'], Dict_Properties['hostName'], Dict_Properties['fullName'], Dict_Properties['managementIp'], Dict_Properties['domainName'], Dict_Properties['dnsConfigAddress'], Dict_Properties['uuid'], Dict_Properties['powerState'], Dict_Properties['inMaintenanceMode'], Dict_Properties['build'], Dict_Properties['vendor'], Dict_Properties['model'], Dict_Properties['serialNumber'], Dict_Properties['connectionState'], Dict_Properties['licenseProductName'], Dict_Properties['licenseProductVersion'], Dict_Properties['managementServerIp'], Dict_Properties['lockdownMode'], Dict_Properties['dasHostState'] ]) else: XLS_Lines.append([ 'No result', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '' ]) if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV, TN_HEADER_ROW, XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA") ConditionnalFormat(TN_WS, 'K2:K' + str(len(XLS_Lines) + 1), 'poweredOn') ConditionnalFormat(TN_WS, 'L2:L' + str(len(XLS_Lines) + 1), 'false') ConditionnalFormat(TN_WS, 'Q2:Q' + str(len(XLS_Lines) + 1), 'connected')
def SheetNSXServices(auth_list, WORKBOOK, TN_WS, NSX_Config={}): NSX_Config['Services'] = [] Dict_Services = {} # Connection to NSX SessionNSX = ConnectNSX(auth_list) services_url = '/policy/api/v1/infra/services' services_json = GetAPI(SessionNSX[0], services_url, auth_list) XLS_Lines = [] TN_HEADER_ROW = ('Services Name', 'Services Entries', 'Service Type', 'Port # / Additionnal Properties', 'Tags', 'Scope') if services_json['result_count'] > 0: for SR in services_json['results']: TAGS = "" SCOPE = "" if 'tags' in SR: tag_list = [] scope_list = [] for tag in SR['tags']: tag_list.append(tag['tag']) scope_list.append(tag['scope']) TAGS = ", ".join(tag_list) SCOPE = ", ".join(scope_list) List_SR = [] List_Proto = [] List_Ports = [] for svc in SR['service_entries']: List_SR.append(svc['display_name']) if 'l4_protocol' in svc: List_Proto.append(svc['l4_protocol']) Ports = ", ".join(svc['destination_ports']) List_Ports.append(Ports) elif 'protocol' in svc: List_Proto.append(svc['protocol']) if "icmp_type" in svc: List_Ports.append(str(svc['icmp_type'])) elif "alg" in svc: List_Proto.append(svc['alg']) Ports = ", ".join(svc['destination_ports']) List_Ports.append(Ports) elif "protocol_number" in svc: List_Proto.append(svc['protocol_number']) elif "ether_type" in svc: List_Proto.append(svc['ether_type']) else: List_Proto.append('IGMP') Proto = "\n".join(List_Proto) svc_ports = "\n".join(List_Ports) Dict_Services['name'] = SR['display_name'] Dict_Services['tags'] = TAGS Dict_Services['scope'] = SCOPE Dict_Services['ports'] = List_Ports Dict_Services['protocols'] = List_Proto Dict_Services['services_entries'] = List_SR NSX_Config['Services'].append(Dict_Services) # Create Line XLS_Lines.append([ SR['display_name'], "\n".join(List_SR), Proto, svc_ports, TAGS, SCOPE ]) else: XLS_Lines.append(['No results', "", "", "", "", ""]) if GetOutputFormat() == 'CSV': CSV = WORKBOOK FillSheetCSV(CSV, TN_HEADER_ROW, XLS_Lines) elif GetOutputFormat() == 'JSON': JSON = WORKBOOK FillSheetJSON(JSON, NSX_Config) elif GetOutputFormat() == 'YAML': YAML = WORKBOOK FillSheetYAML(YAML, NSX_Config) else: FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")