Ejemplo n.º 1
0
def SheetSummary(auth_list,WORKBOOK,TN_WS, NSX_Config = {}):
    # Connection to NSX
    SessionNSX = ConnectNSX(auth_list)
    system_url = '/api/v1/ui-controller/system-aggregate-status'
    inventory_url = '/api/v1/ui-controller/inventory-aggregate-status'
    security_url = '/api/v1/ui-controller/security-aggregate-status'
    network_url = '/api/v1/ui-controller/networking-aggregate-status'
    fabric_url = '/api/v1/ui-controller/fabric-aggregate-status'
    inventory_json = GetAPI(SessionNSX[0],inventory_url, auth_list)
    security_json = GetAPI(SessionNSX[0],security_url, auth_list)
    network_json = GetAPI(SessionNSX[0],network_url, auth_list)
    fabric_json = GetAPI(SessionNSX[0],fabric_url, auth_list)
    system_json = GetAPI(SessionNSX[0],system_url, auth_list)

    XLS_Lines = []
    TN_HEADER_ROW = (' ', 'Number', 'Alarms', 'Status')
    XLS_Lines = GetEntity(system_json, XLS_Lines)
    XLS_Lines = GetEntity(fabric_json, XLS_Lines)
    XLS_Lines = GetEntity(inventory_json, XLS_Lines)
    XLS_Lines = GetEntity(network_json, XLS_Lines)
    XLS_Lines = GetEntity(security_json, XLS_Lines)

    a1 = TN_WS['A1']
    a1.font = Font(name='Arial', size=16, bold=True)
    a1.value = "Summary"
    TN_WS[3]
    FillSheet(WORKBOOK,TN_WS.title,TN_HEADER_ROW,XLS_Lines,"0072BA", "TableStyleLight9", True, start_cell = 'A4')
    ConditionnalFormat(TN_WS, 'D5:D' + str(len(XLS_Lines) + 4), 'UP', False, 'GREEN')
    ConditionnalFormat(TN_WS, 'D5:D' + str(len(XLS_Lines) + 4), 'NONE', False, 'ORANGE')
    ConditionnalFormat(TN_WS, 'D5:D' + str(len(XLS_Lines) + 4), 'UP')
Ejemplo n.º 2
0
def GetTNTunnels(auth_list):
    SessionNSX = ConnectNSX(auth_list)
    transport_node_json = GetAPI(SessionNSX[0],'/api/v1/transport-nodes', auth_list)
    transport_nodes = (transport_node_json['results'])
    tnode_dict = {}
    
    for n in range(len(transport_nodes)):
        tnode_dict.update({transport_nodes[n]['node_id']:transport_nodes[n]['display_name']})
        
    for uuid in tnode_dict.items():
        try:
            tunnel_url = '/api/v1/transport-nodes/' + str(uuid[0]) + '/tunnels'
            tunnel_json = GetAPI(SessionNSX[0],tunnel_url, auth_list)
            print('\nTransport Node: ' + style.ORANGE + uuid[1] + style.NORMAL)
            print('')
            x = (len(tunnel_json['tunnels']))
            
            if x > 0:
                for n  in range(x):
                    print('Tunnel name: ',tunnel_json['tunnels'][n]['name'])
                    if tunnel_json['tunnels'][n]['status'] == 'UP': print('Tunnel Status: ' + style.GREEN + tunnel_json['tunnels'][n]['status'] + style.NORMAL)
                    else: print('Tunnel Status: ' + style.RED + tunnel_json['tunnels'][n]['status'] + style.NORMAL)
                    print('Egress Interface: ',tunnel_json['tunnels'][n]['egress_interface'])
                    print('Local Tunnel IP: ',tunnel_json['tunnels'][n]['local_ip'])
                    print('Remote Tunnel IP: ',tunnel_json['tunnels'][n]['remote_ip'])
                    print('Remote Node ID: ',tunnel_json['tunnels'][n]['remote_node_id'])
                    print('Remote Node: ',tunnel_json['tunnels'][n]['remote_node_display_name'])
                    print('Tunnel Encapsulation: ',tunnel_json['tunnels'][n]['encap'])
                    print('')
            else:
                print(style.RED + '**** No tunnels exist for this transport node ****' + style.NORMAL)
        except:
            print(style.RED + '**** No tunnels exist for this transport node ****\n' + style.NORMAL)
Ejemplo n.º 3
0
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)")

    FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
Ejemplo n.º 4
0
def SheetSecPol(auth_list, WORKBOOK, TN_WS, NSX_Config={}):
    NSX_Config['Policies'] = []
    Dict_Policies = {}
    # connection to NSX
    SessionNSX = ConnectNSX(auth_list)
    policies_json = GetAPI(
        SessionNSX[0],
        '/policy/api/v1/infra/domains/default/security-policies', auth_list)
    # Header of Excel and initialization of lines
    XLS_Lines = []
    TN_HEADER_ROW = ('Security Policy ID', 'Security Policy Name',
                     'NSX Policy Path', 'Sequence Number', 'Category',
                     'is Stateful')

    if isinstance(
            policies_json, dict
    ) and 'results' in policies_json and policies_json['result_count'] > 0:
        for policy in policies_json["results"]:
            Dict_Policies['id'] = policy['id']
            Dict_Policies['name'] = policy['display_name']
            Dict_Policies['path'] = policy['path']
            Dict_Policies['sequence_number'] = policy['sequence_number']
            Dict_Policies['category'] = policy['category']
            Dict_Policies['stateful'] = policy['stateful']
            NSX_Config['Policies'].append(Dict_Policies)
            XLS_Lines.append([
                policy['id'], policy['display_name'], policy['path'],
                policy['sequence_number'], policy['category'],
                policy['stateful']
            ])
    else:
        XLS_Lines.append(['No results', "", "", "", "", ""])
    FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
Ejemplo n.º 5
0
def GetLRSum(auth_list):
    SessionNSX = ConnectNSX(auth_list)
    lr_list_json = GetAPI(SessionNSX[0],'/api/v1/logical-routers', auth_list)
    total_lrs = lr_list_json["result_count"]
    
    tier0s = 0
    tier0vrfs = 0
    tier1s = 0

    for i in lr_list_json["results"]:
        if i['router_type'] == 'TIER0': 
            tier0s +=1
        elif i['router_type'] == 'VRF': 
            tier0vrfs +=1
        elif i['router_type'] == 'TIER1':
            tier1s +=1

    print("\n========================================================================================================\n")
    print('Tier0 Logical Routers:\t' + style.ORANGE + str(tier0s) + style.NORMAL)
    print('Tier0 VRFs:\t\t' + style.ORANGE + str(tier0vrfs) + style.NORMAL)
    print('Tier1 Logical Routers:\t' + style.ORANGE + str(tier1s) + style.NORMAL)
    print('\nTotal Number of Logical Routers: ' + style.ORANGE + str(total_lrs) + style.NORMAL + "\n")
    
    for i in lr_list_json["results"]:
        print('\nName:\t\t' + style.ORANGE + i['display_name'] + style.NORMAL)
        print('Router Type:\t' + style.ORANGE + i['router_type'] + style.NORMAL)
        print('HA Mode:\t' + style.ORANGE + i['high_availability_mode'] + style.NORMAL)
    
    print("\n========================================================================================================")
Ejemplo n.º 6
0
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"]:
            bgpstatus_url = "/policy/api/v1/infra/tier-0s/" + t0['display_name'] + "/locale-services/default/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========================================================================================================")
Ejemplo n.º 7
0
def SheetTZ(auth_list,WORKBOOK,TN_WS, NSX_Config ={} ):
    NSX_Config['TZ'] = []
    Dict_TZ = {}
    # Connect NSX
    SessionNSX = ConnectNSX(auth_list)
    stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1])
    
    XLS_Lines = []
    TN_HEADER_ROW = ('Name', 'Description', 'ID', 'Ressource Type', 'Host Switch ID', 'Hos Switch Mode', 'Host Switch Name', 'Host Switch is Default', 'is Nested NSX', 'Transport Type', 'Uplink Teaming Policy Name')

    tz_list = TransportZones(stub_config).list()
    for TZ in tz_list.results:
        tz = TZ.convert_to(TransportZone)
        if tz.uplink_teaming_policy_names is not None:
            TZ_Teaming = "\n".join(tz.uplink_teaming_policy_names)
        else:
            TZ_Teaming = ""
        Dict_TZ['name'] = tz.display_name
        Dict_TZ['description'] = tz.description
        Dict_TZ['id'] = tz.id
        Dict_TZ['resource_type'] = tz.resource_type
        Dict_TZ['host_swithc_id'] = tz.host_switch_id
        Dict_TZ['host_switch_mode'] = tz.host_switch_mode
        Dict_TZ['host_switch_name'] = tz.host_switch_name
        Dict_TZ['is_default'] = tz.is_default
        Dict_TZ['nested'] = tz.nested_nsx
        Dict_TZ['type'] = tz.transport_type
        Dict_TZ['teaming'] = tz.uplink_teaming_policy_names
        NSX_Config['TZ'].append(Dict_TZ)
        # Create line
        XLS_Lines.append([tz.display_name, tz.description, tz.id, tz.resource_type, tz.host_switch_id, tz.host_switch_mode, tz.host_switch_name, tz.is_default, tz.nested_nsx, tz.transport_type, TZ_Teaming])

    FillSheet(WORKBOOK,TN_WS.title,TN_HEADER_ROW,XLS_Lines,"0072BA")
        
Ejemplo n.º 8
0
def SheetSecDFW(auth_list, WORKBOOK, TN_WS, NSX_Config={}):
    NSX_Config['DFW'] = []
    # connection to NSX
    SessionNSX = ConnectNSX(auth_list)
    policies_json = GetAPI(
        SessionNSX[0],
        '/policy/api/v1/infra/domains/default/security-policies', auth_list)
    stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1])
    rules_svc = Rules(stub_config)
    # Header of Excel and initialization of lines
    XLS_Lines = []
    TN_HEADER_ROW = ('Security Policy', 'Security Policy Applied to',
                     'Category', 'Rule Name', 'Rule ID', 'Source',
                     'Destination', 'Services', 'Profiles', 'Rule Applied to',
                     'Action', 'Direction', 'Disabled', 'IP Protocol',
                     'Logged')
    if isinstance(policies_json, dict) and 'results' in policies_json:
        for policy in policies_json["results"]:
            # Check Applied to for policies
            scopelist = GetListNameFromPath(policy['scope'])
            ####  Get RULES       ####
            PrintRulesbyCategory(rules_svc, policy['display_name'],
                                 policy['id'], policy['category'], scopelist,
                                 XLS_Lines, NSX_Config)
    else:
        XLS_Lines.append(
            ['No results', "", "", "", "", "", "", "", "", "", "", "", "", ""])

    FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
Ejemplo n.º 9
0
def GetComputeDetail(auth_list):
    SessionNSX = ConnectNSX(auth_list)
    cmp_mgr_json = GetAPI(SessionNSX[0], '/api/v1/fabric/compute-managers',
                          auth_list)
    cmp_managers = cmp_mgr_json["result_count"]

    print(
        "\n========================================================================================================"
    )
    print('\nNumber of Compute Managers: ' + style.ORANGE + str(cmp_managers) +
          style.NORMAL)

    for i in range(cmp_mgr_json["result_count"]):
        print('\nCompute Manager ID:\t' + style.ORANGE +
              cmp_mgr_json["results"][i]["id"] + style.NORMAL)
        print('Compute Manager Server:\t' + style.ORANGE +
              cmp_mgr_json["results"][i]["server"] + style.NORMAL)
        print('Compute Manager Origin:\t' + style.ORANGE +
              cmp_mgr_json["results"][i]["origin_type"] + style.NORMAL)
        print('Compute Manager Build:\t' + style.ORANGE +
              cmp_mgr_json["results"][i]["origin_properties"][0].get("value") +
              style.NORMAL)
    print(
        "\n========================================================================================================"
    )
Ejemplo n.º 10
0
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("========================================================================================================")
Ejemplo n.º 11
0
def SheetTunnels(auth_list, WORKBOOK, TN_WS, NSX_Config={}):
    NSX_Config['Tunnels'] = []
    # Connect to NSX
    SessionNSX = ConnectNSX(auth_list)
    transport_node_url = '/api/v1/transport-nodes'
    transport_node_json = GetAPI(SessionNSX[0], transport_node_url, auth_list)
    XLS_Lines = []
    TN_HEADER_ROW = ('Transport Node', 'Tunnel Name', 'Tunnel Status',
                     'Egress Interface', 'Local Tunnel IP', 'Remote Tunnel IP',
                     'Remote Node ID', 'Remote Node Name', 'Encap')
    # Check if Transport Node present
    if isinstance(
            transport_node_json,
            dict) and 'results' in transport_node_json and transport_node_json[
                'result_count'] > 0:
        for node in transport_node_json['results']:
            tunnel_url = '/api/v1/transport-nodes/' + node['id'] + '/tunnels'
            tunnel_json = GetAPI(SessionNSX[0], tunnel_url, auth_list)
            if tunnel_json["result_count"] > 0:
                Dict_NodesTunnels = {}
                Dict_NodesTunnels['node_name'] = node['display_name']
                Dict_NodesTunnels['tunnels'] = []
                Dict_Tunnels = {}
                for tunnel in tunnel_json["tunnels"]:
                    Dict_Tunnels['name'] = tunnel['name']
                    Dict_Tunnels['status'] = tunnel['status']
                    Dict_Tunnels['Egress_int'] = tunnel['egress_interface']
                    Dict_Tunnels['local_ip'] = tunnel['local_ip']
                    Dict_Tunnels['remote_ip'] = tunnel['remote_ip']
                    Dict_Tunnels['remote_node_id'] = tunnel['remote_node_id']
                    Dict_Tunnels['remote_node_display_name'] = tunnel[
                        'remote_node_display_name']
                    Dict_Tunnels['encap'] = tunnel['encap']
                    Dict_NodesTunnels['tunnels'].append(Dict_Tunnels)
                    # Create line
                    XLS_Lines.append([
                        node['display_name'], tunnel['name'], tunnel['status'],
                        tunnel['egress_interface'], tunnel['local_ip'],
                        tunnel['remote_ip'], tunnel['remote_node_id'],
                        tunnel['remote_node_display_name'], tunnel['encap']
                    ])

                NSX_Config['Tunnels'].append(Dict_NodesTunnels)
    else:
        XLS_Lines.append(
            ["no Transport Nodes", "", "", "", "", "", "", "", ""])

    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, 'C2:C' + str(len(XLS_Lines) + 1), 'UP')
Ejemplo n.º 12
0
def SheetSegments(auth_list, WORKBOOK, TN_WS, NSX_Config={}):
    NSX_Config['Segments'] = []
    Dict_LS = {}

    # Connect to NSX
    SessionNSX = ConnectNSX(auth_list)
    segments_url = '/api/v1/logical-switches'
    segments_json = GetAPI(SessionNSX[0], segments_url, auth_list)
    tz_url = '/policy/api/v1/infra/sites/default/enforcement-points/default/transport-zones'
    tz_json = GetAPI(SessionNSX[0], tz_url, auth_list)

    XLS_Lines = []
    TN_HEADER_ROW = ('Segments', 'VNI', 'VLAN', 'Transport Zone Name',
                     'Transport Zone Type', 'Replication Mode', 'Admin State')

    # Check if Segements present
    if isinstance(
            segments_json, dict
    ) and 'results' in segments_json and segments_json['result_count'] > 0:
        for segment in segments_json['results']:
            TZ_NAME = ""
            TZ_Type = ""
            Dict_LS['vni'] = ''
            Dict_LS['vlan'] = ''
            for tz in tz_json['results']:
                if segment['transport_zone_id'] == tz['id']:
                    TZ_NAME = tz['display_name']
                    TZ_Type = tz['tz_type']
                    break
            Dict_LS['segment_name'] = segment['display_name']
            if 'vni' in segment: Dict_LS['vni'] = segment['vni']
            if 'vlan' in segment: Dict_LS['vlan'] = segment['vlan']
            Dict_LS['tz_name'] = TZ_NAME
            Dict_LS['tz_type'] = TZ_Type
            if 'replication_mode' in segment:
                Dict_LS['replication_mode'] = segment['replication_mode']
            Dict_LS['status'] = segment['admin_state']
            NSX_Config['Segments'].append(Dict_LS)
            XLS_Lines.append([
                Dict_LS['segment_name'], Dict_LS['vni'], Dict_LS['vlan'],
                TZ_NAME, TZ_Type, Dict_LS['replication_mode'],
                segment['admin_state']
            ])
    else:
        XLS_Lines.append(["no Segments", "", "", "", "", "", ""])

    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, 'G2:G' + str(len(XLS_Lines) + 1), 'UP')
Ejemplo n.º 13
0
def SheetSegments(auth_list,WORKBOOK,TN_WS,NSX_Config = {}):
    NSX_Config['Segments'] = []
    Dict_LS = {}
    # NSX Connection
    SessionNSX = ConnectNSX(auth_list)
    stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1])
    ls_svc = LogicalSwitches(stub_config)
    ls_list = ls_svc.list()
    nb = len(ls_list.results)
    tz_svc = TransportZones(stub_config)
    tz_list = tz_svc.list()

    XLS_Lines = []
    TN_HEADER_ROW = ('Segments', 'VNI', 'VLAN', 'Transport Zone Name', 'Transport Zone Type', 'Replication Mode', 'Admin State')

    if ls_list.result_count > 0:
        while True:
            for segment in ls_list.results:
                TZ_NAME = ""
                TZ_Type = ""
                for tz in tz_list.results:
                    if segment.transport_zone_id == tz.id:
                        TZ_NAME = tz.display_name
                        TZ_Type = tz.transport_type

                Dict_LS['segment_name'] = segment.display_name
                Dict_LS['vni'] = segment.vni
                Dict_LS['vlan'] = segment.vlan
                Dict_LS['tz_name'] = TZ_NAME
                Dict_LS['tz_type'] = TZ_Type
                Dict_LS['replication_mode'] = segment.replication_mode
                Dict_LS['status'] = segment.admin_state
                NSX_Config['Segments'].append(Dict_LS)
                XLS_Lines.append([segment.display_name, segment.vni, segment.vlan, TZ_NAME, TZ_Type, segment.replication_mode,segment.admin_state])

            if ls_list.cursor is None:
                break
            else:
                print(" --> more than " + str(nb) + " results for " + style.RED + "Segments" + style.NORMAL + " - please wait")
                ls_list = LogicalSwitches(stub_config).list(cursor =ls_list.cursor )
                nb = len(ls_list.results) + nb


    else:
        XLS_Lines.append(["no Segments", "", "", "", "", "",""])

    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, 'G2:G' + str(len(XLS_Lines) + 1), 'UP')
Ejemplo n.º 14
0
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)
    YAML_DICT = GetYAMLDict()

    #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)
Ejemplo n.º 15
0
def GetVMidByLPid(auth_list, lp_id):
    SessionNSX = ConnectNSX(auth_list)
    vif_url = '/api/v1/fabric/vifs?lport_attachment_id=' + lp_id
    vif_json = GetAPI(SessionNSX[0], vif_url, auth_list)
    if isinstance(
            vif_json,
            dict) and 'results' in vif_json and vif_json['result_count'] == 1:
        vif = vif_json['results']
        return str(vif[0]['owner_vm_id'])
    return ''
Ejemplo n.º 16
0
def GetVMNamebyID(auth_list, vm_id):
    SessionNSX = ConnectNSX(auth_list)
    vm_url = '/api/v1/fabric/virtual-machines?external_id=' + vm_id
    vm_json = GetAPI(SessionNSX[0], vm_url, auth_list)
    if isinstance(
            vm_json,
            dict) and 'results' in vm_json and vm_json['result_count'] == 1:
        vm = vm_json['results']
        return str(vm[0]['display_name'])
    return ''
Ejemplo n.º 17
0
def SheetNSXManagerInfo(auth_list,WORKBOOK,TN_WS, NSX_Config = {}):
    Dict_NSXManager = {}     # Dict NSXManager initialization
    NSX_Config['NSXManager'] = Dict_NSXManager
 
    SessionNSX = ConnectNSX(auth_list)
    ########### SECTION FOR REPORTING ON NSX-T MANAGER CLUSTER ###########
    nsxclstr_url = '/api/v1/cluster/status'
    nsxclstr_json = GetAPI(SessionNSX[0],nsxclstr_url, auth_list)
    # Check online and offline nodes
    if 'online_nodes' in nsxclstr_json['mgmt_cluster_status']:
        online_nodes = str(len(nsxclstr_json['mgmt_cluster_status']['online_nodes']))
    else:
        online_nodes = "0"
    if 'offline_nodes' in nsxclstr_json['mgmt_cluster_status']:
        offline_nodes = str(len(nsxclstr_json['mgmt_cluster_status']['offline_nodes']))
    else:
        offline_nodes = "0"
    
    NSX_Config['NSXManager']['Cluster_id'] = nsxclstr_json['cluster_id']
    NSX_Config['NSXManager']['Cluster_status'] = nsxclstr_json['mgmt_cluster_status']['status']
    NSX_Config['NSXManager']['Cluster_ctrl_status'] = nsxclstr_json['control_cluster_status']['status']
    NSX_Config['NSXManager']['Cluster_overall_status'] = nsxclstr_json['detailed_cluster_status']['overall_status']
    NSX_Config['NSXManager']['Cluster_online_nodes'] = online_nodes
    NSX_Config['NSXManager']['Cluster_offline_nodes'] = offline_nodes
    # Summary Table
    XLS_Lines = [['NSX-T Cluster ID', nsxclstr_json['cluster_id']], ['NSX-T Cluster Status', nsxclstr_json['mgmt_cluster_status']['status']], ['NSX-T Control Cluster Status', nsxclstr_json['control_cluster_status']['status']] , ['Overall NSX-T Cluster Status', nsxclstr_json['detailed_cluster_status']['overall_status']], ['Number of online nodes', online_nodes], ['Number of offline nodes', offline_nodes]]
    idx_second_sheet = len(XLS_Lines) + 2
    # Write in Excel
    for line in XLS_Lines:
    	TN_WS.append(line)
    
    # Format 1st Sheet
    for i in range(1, len(XLS_Lines) + 1):
        TN_WS.cell(row=i, column=1).fill = PatternFill('solid', start_color='004F81BD', end_color='004F81BD') #Blue
        TN_WS.cell(row=i, column=1).font = Font(b=True, color="00FFFFFF") #White

    ConditionnalFormat(TN_WS, 'B2:B4', 'STABLE')
    ConditionnalFormat(TN_WS, 'B5:B5', '3')
    ConditionnalFormat(TN_WS, 'B6:B6', '0')

    # Create second sheet
    TN_WS[idx_second_sheet]
    XLS_Lines = []
    TN_HEADER_ROW = ('Group ID', 'Group Type', 'Group Status','Member FQDN', 'Member IP address', 'Member UUID', 'Member Status')
    for group in nsxclstr_json['detailed_cluster_status']['groups']:
        for member in group['members']:
            XLS_Lines.append([group['group_id'],group['group_type'], group['group_status'], member['member_fqdn'], member['member_ip'], member['member_uuid'], member['member_status']])

    startCell = "A" + str(idx_second_sheet + 1)
    FillSheet(WORKBOOK,TN_WS.title,TN_HEADER_ROW,XLS_Lines,"0072BA", "TableStyleLight9", False, startCell)
    ConditionnalFormat(TN_WS, 'G10:G' + str(len(XLS_Lines) + 1), 'UP')
    ConditionnalFormat(TN_WS, 'C10:C' + str(len(XLS_Lines) + 1), 'STABLE')
Ejemplo n.º 18
0
def GetDFWRulesVNIC(auth_list):
    SessionNSX = ConnectNSX(auth_list)
    lp_url = '/api/v1/logical-ports'
    lp_json = GetAPI(SessionNSX[0], lp_url, auth_list)

    tab = []
    if isinstance(
            lp_json,
            dict) and 'results' in lp_json and lp_json['result_count'] > 0:
        print(
            "\n========================================================================================================"
        )
        print(
            '\n----------------------------------- DFW Rules per VNIC -------------------------------------------'
        )
        print(
            '| Rule-count |                 VIF ID                 |                  VM name                 |'
        )
        print(
            '--------------------------------------------------------------------------------------------------'
        )
        # If VIF only
        for lp in lp_json['results']:
            vm_name = ''
            lp_id = ''
            if 'attachment' in lp:
                attach = lp['attachment']
                if attach['attachment_type'] == 'VIF':
                    lp_id = attach['id']
                    vm_id = GetVMidByLPid(auth_list, lp_id)
                    if vm_id != '':
                        vm_name = GetVMNamebyID(auth_list, vm_id)

                    dfw_vnic_url = '/api/v1/firewall/sections?applied_tos=' + lp[
                        'internal_id'] + '&deep_search=true'
                    dfw_vnic_json = GetAPI(SessionNSX[0], dfw_vnic_url,
                                           auth_list)
                    tab.append([
                        dfw_vnic_json['result_count'], lp_id,
                        '{:40.40}'.format(vm_name)
                    ])

    for i in tab:
        if len(i) > 1:
            print('  {:^12d} {:<40}  {:<40}'.format(i[0], i[1], i[2]))
    print(
        '--------------------------------------------------------------------------------------------------'
    )
    print(
        "\n========================================================================================================"
    )
Ejemplo n.º 19
0
def GetEdgeCLDetail(auth_list):
    SessionNSX = ConnectNSX(auth_list)
    edgecluster_json = GetAPI(SessionNSX[0],'/api/v1/edge-clusters', auth_list)
    edgeclusters = (edgecluster_json["result_count"])
    
    print("\n========================================================================================================")
    for n in range(edgeclusters):
        print('')
        print('Edge Cluster: ' + style.ORANGE + edgecluster_json["results"][n]["display_name"] + style.NORMAL)
        print('Resource Type: ' + style.ORANGE + edgecluster_json["results"][n]["resource_type"] + style.NORMAL)
        print('Deployment Type: ' + style.ORANGE + edgecluster_json["results"][n]["deployment_type"] + style.NORMAL)
        print('Member Node Type: ' + style.ORANGE + edgecluster_json["results"][n]["member_node_type"] + style.NORMAL)
        print('')
    print("========================================================================================================")
Ejemplo n.º 20
0
def GetInventoryUsage(auth_list):
    SessionNSX = ConnectNSX(auth_list)
    nsx_inv_cap_json = GetAPI(SessionNSX[0],'/api/v1/capacity/usage?category=inventory', auth_list)
    print("\n========================================================================================================")
    print('\n------------------------------------ NSX INVENTORY CAPACITY -----------------------------------')
    print('|  Name                                                 | Current  | Max Supported | Usage %  |')
    print('-----------------------------------------------------------------------------------------------')

    data = nsx_inv_cap_json['capacity_usage']
    cap_inv = len(data)
    for n in range(cap_inv):
        if data[n]['current_usage_percentage'] > 70: print('{:<60s}{:>4d}{:>12d}\x1b[0;31;40m{:>15.1f}\x1b[0m'.format(data[n]['display_name'],data[n]['current_usage_count'],data[n]['max_supported_count'],data[n]['current_usage_percentage']))
        else: print('{:<60s}{:>4d}{:>12d}{:>15.1f}'.format(data[n]['display_name'],data[n]['current_usage_count'],data[n]['max_supported_count'],data[n]['current_usage_percentage']))
    print('-----------------------------------------------------------------------------------------------')
    print("\n========================================================================================================")
Ejemplo n.º 21
0
def GetHealthNSXCluster(auth_list):
    SessionNSX = ConnectNSX(auth_list)
    nsxclstr_json = GetAPI(SessionNSX[0], '/api/v1/cluster/status', auth_list)

    print(
        "\n========================================================================================================"
    )
    if nsxclstr_json['mgmt_cluster_status']['status'] == 'STABLE':
        print('NSX-T Cluster Status:\t\t' + style.GREEN +
              nsxclstr_json['mgmt_cluster_status']['status'] + style.NORMAL)
    else:
        print('NSX-T Cluster Status:\t\t' + style.RED +
              nsxclstr_json['mgmt_cluster_status']['status'] + style.NORMAL)
    if nsxclstr_json['control_cluster_status']['status'] == 'STABLE':
        print('NSX-T Control Cluster Status:\t' + style.GREEN +
              nsxclstr_json['control_cluster_status']['status'] + style.NORMAL)
    if nsxclstr_json['detailed_cluster_status']['overall_status'] == 'STABLE':
        print('NSX-T Overall Cluster:\t\t' + style.GREEN +
              nsxclstr_json['detailed_cluster_status']['overall_status'] +
              style.NORMAL)
    else:
        print('NSX-T Overall Cluster:\t\t' + style.RED +
              nsxclstr_json['detailed_cluster_status']['overall_status'] +
              style.NORMAL)
    online_nodes = len(nsxclstr_json['mgmt_cluster_status']['online_nodes'])

    groups = nsxclstr_json['detailed_cluster_status']['groups']
    nsxmgr_json = GetAPI(SessionNSX[0], '/api/v1/cluster', auth_list)
    base = nsxmgr_json["nodes"]

    for n in range(online_nodes):
        print('\nNSX-T Manager Appliance: ' + style.ORANGE + base[n]['fqdn'] +
              style.NORMAL)
        for n in range(len(groups)):
            print('\nGroup Type:\t' + groups[n]['group_type'].strip())
            if groups[n]['group_status'] == 'STABLE':
                print('Group Status:\t' + style.GREEN +
                      groups[n]['group_status'] + style.NORMAL)
            else:
                print('Group Status:\t\t' + style.RED +
                      groups[n]['group_status'] + style.NORMAL)
    print(
        "========================================================================================================"
    )
Ejemplo n.º 22
0
def SheetT1Segments(auth_list, WORKBOOK, TN_WS, NSX_Config={}):
    NSX_Config['T1Segments'] = []
    Dict_Segments = {}
    # Connect to NSX
    SessionNSX = ConnectNSX(auth_list)
    t1_url = '/policy/api/v1/infra/tier-1s'
    t1_json = GetAPI(SessionNSX[0], t1_url, auth_list)

    XLS_Lines = []
    TN_HEADER_ROW = ('Tier1 Segment Name', 'Tier1 Segment ID',
                     'Segment Gateway', 'Segment Network', 'Tier1 Router Name',
                     'Tier1 Router ID')

    if isinstance(
            t1_json,
            dict) and 'results' in t1_json and t1_json['result_count'] > 0:
        for i in t1_json["results"]:
            t1_segment_url = '/policy/api/v1/search?query=resource_type:Segment&&dsl=segment where connectivity path=' + str(
                i['path']) + ''
            t1_segment_json = GetAPI(SessionNSX[0], t1_segment_url, auth_list)

            for n in t1_segment_json["results"]:
                Dict_Segments['id'] = n['id']
                Dict_Segments['name'] = n['display_name']
                Dict_Segments['gw'] = n['subnets'][0]['gateway_address']
                Dict_Segments['subnet'] = n['subnets'][0]['network']
                Dict_Segments['router'] = i['display_name']
                Dict_Segments['path'] = str(
                    n['connectivity_path']).split("/")[3]
                NSX_Config['T1Segments'].append(Dict_Segments)
                XLS_Lines.append([
                    n['display_name'], n['id'],
                    n['subnets'][0]['gateway_address'],
                    n['subnets'][0]['network'], i['display_name'],
                    str(n['connectivity_path']).split("/")[3]
                ])

    else:
        XLS_Lines.append(["no result", "", "", "", "", ""])

    FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
Ejemplo n.º 23
0
def SheetSecDFW(auth_list,WORKBOOK,TN_WS, NSX_Config = {}):
    NSX_Config['DFW'] = []
    # connection to NSX
    SessionNSX = ConnectNSX(auth_list)
    policies_json = GetAPI(SessionNSX[0],'/policy/api/v1/infra/domains/default/security-policies', auth_list)
    # Get all groups - to get display name
    domain_id = 'default'
    # Connection for get Groups criteria - REST/API
    groups_json = GetAPI(SessionNSX[0],'/policy/api/v1/infra/domains/' + domain_id + '/groups', auth_list)
    # Get All Services
    services_json = GetAPI(SessionNSX[0],'/policy/api/v1/infra/services', auth_list)
    # Get all Contewxt Profile
    context_json = GetAPI(SessionNSX[0],'/policy/api/v1/infra/context-profiles', auth_list)

    # Header of Excel and initialization of lines
    XLS_Lines = []
    TN_HEADER_ROW = ('Security Policy', 'Security Policy Applied to', 'Category','Rule Name', 'Rule ID','Source', 'Destination', 'Services', 'Profiles', 'Rule Applied to', 'Action', 'Direction', 'Disabled', 'IP Protocol', 'Logged')
    if isinstance(policies_json, dict) and 'results' in policies_json: 
        for policy in policies_json["results"]:
            # Check Applied to for policies
            scopelist= GetListNameFromPath(policy['scope'], groups_json)
            ####  Get RULES       ####
            domain_id = 'default'
            rules_url = '/policy/api/v1/infra/domains/' + domain_id + '/security-policies/' + policy['id'] + '/rules/'
            rules_json = GetAPI(SessionNSX[0],rules_url, auth_list)
            PrintRulesbyCategory(rules_json, groups_json, services_json, context_json, policy['display_name'],policy['id'],policy['category'], scopelist, XLS_Lines, NSX_Config)
    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")
Ejemplo n.º 24
0
def SheetTZ(auth_list,WORKBOOK,TN_WS, NSX_Config ={} ):
    NSX_Config['TZ'] = []
    # Connect NSX
    SessionNSX = ConnectNSX(auth_list)
    transport_zone_url = '/api/v1/transport-zones'
    transport_zone_json = GetAPI(SessionNSX[0],transport_zone_url, auth_list)
    XLS_Lines = []
    TN_HEADER_ROW = ('Name', 'ID', 'Ressource Type', 'Host Switch ID', 'Host Switch Mode', 'Host Switch Name', 'Host Switch is Default', 'is Nested NSX', 'Transport Type')
    if isinstance(transport_zone_json, dict) and 'results' in transport_zone_json and transport_zone_json['result_count'] > 0: 
        for TZ in transport_zone_json['results']:
            Dict_TZ = {}
            Dict_TZ['name'] = TZ['display_name']
            Dict_TZ['id'] = TZ['id']
            Dict_TZ['resource_type'] = TZ['resource_type']
            Dict_TZ['host_swithc_id'] = TZ['host_switch_id']
            Dict_TZ['host_switch_mode'] = TZ['host_switch_mode']
            Dict_TZ['host_switch_name'] = TZ['host_switch_name']
            Dict_TZ['is_default'] = TZ['is_default']
            Dict_TZ['nested'] = TZ['nested_nsx']
            Dict_TZ['type'] = TZ['transport_type']
            NSX_Config['TZ'].append(Dict_TZ)
            # Create line
            XLS_Lines.append([TZ['display_name'], TZ['id'], TZ['resource_type'], TZ['host_switch_id'], TZ['host_switch_mode'], TZ['host_switch_name'], TZ['is_default'], TZ['nested_nsx'], TZ['transport_type']])
    else:
        XLS_Lines.append(['no Transport Zones', '', '', '', '', '', '', '', ''])

    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")
        
Ejemplo n.º 25
0
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)
    stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1])
    ipsvc = IpAddresses(stub_config)
    vmsvc = VirtualMachines(stub_config)
    sgmntsvc = Segments(stub_config)
    sgmntprtsvc = SegmentPorts(stub_config)

    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
            for nbcriteria in group['expression']:
                criteria = GetCriteria(SessionNSX[0], auth_list, nbcriteria)

            # Create IP Address List for each group
            IPList_Obj = ipsvc.list(domain_id, group['id'])
            IP = ""
            if IPList_Obj.result_count > 0:
                IP = ', '.join(IPList_Obj.results)

            # Create Virtual Machine List for each group
            VMList_Obj = vmsvc.list(domain_id, group['id'])
            VM = ""
            VMList = []
            if VMList_Obj.result_count > 0:
                for vm in VMList_Obj.results:
                    VMList.append(vm.display_name)

                VM = ', '.join(VMList)

            # Create Segment List for each group
            SegList_Obj = sgmntsvc.list(domain_id, group['id'])
            Segment = ""
            SegList = []
            if SegList_Obj.result_count > 0:
                for seg in SegList_Obj.results:
                    SegList.append(seg.display_name)

                Segment = ', '.join(SegList)

            # Create Segment Port/vNIC List for each group
            SegPortList_Obj = sgmntprtsvc.list(domain_id, group['id'])
            SegPort = ""
            SegPortList = []
            if SegPortList_Obj.result_count > 0:
                for segport in SegPortList_Obj.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'] = IPList_Obj.results
            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', "", "", "", "", "", "", "", ""])

    FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
Ejemplo n.º 26
0
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', "", "", "", "", ""])

    FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
Ejemplo n.º 27
0
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)
    stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1])
    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"]})

    # Alarms extract
    alarms_svc = Alarms(stub_config)
    alarms_list = alarms_svc.list()
    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 alarms_list.result_count > 0:
        for alarm in alarms_list.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
    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')
Ejemplo n.º 28
0
def SheetFabDiscoveredNodes(auth_list, WORKBOOK, TN_WS, NSX_Config={}):

    SessionNSX = ConnectNSX(auth_list)
    stub_config = StubConfigurationFactory.new_std_configuration(SessionNSX[1])
    disc_node_list = DiscoveredNodes(stub_config).list()

    Dict_DiscoveredNodes = {}  # Dict Discovered nodes initialization
    NSX_Config['DiscoveredNodes'] = []
    # Construct Line
    XLS_Lines = []
    if disc_node_list.result_count > 0:
        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')
        for node in disc_node_list.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']
            Dict_DiscoveredNodes['domainName'] = Dict_Properties['domainName']
            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 = ('No result', '', '', '', '', '', '', '', '', '', '', '',
                     '', '', '', '', '', '', '', '', '', '')

    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')
Ejemplo n.º 29
0
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', "", "", "", "", "", "", ""])

    FillSheet(WORKBOOK, TN_WS.title, TN_HEADER_ROW, XLS_Lines, "0072BA")
Ejemplo n.º 30
0
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", "", "", "", "", "", "", "", "", "", ""])

    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),
                           'ESTABLISHED')
        ConditionnalFormat(TN_WS, 'B2:B' + str(len(XLS_Lines) + 1), 'TRUE')