コード例 #1
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')
コード例 #2
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')
コード例 #3
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')
コード例 #4
0
ファイル: docs_summary.py プロジェクト: ysi/nsx-powerops
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]

    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",
                  "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')
コード例 #5
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
        ])

    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")
コード例 #6
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', "", "", "", "", ""])

    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")
コード例 #7
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")
コード例 #8
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", "", "", "", "", ""])
    
    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")
コード例 #9
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', "", "", "", "", "", "", "", "", "", "", "", "", ""])

    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")
コード例 #10
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")
        
コード例 #11
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
    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')
コード例 #12
0
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')
コード例 #13
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')
コード例 #14
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', "", "", "", "", "", "", ""])

    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")
コード例 #15
0
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
            EdgeID = None
            HAStatus = None
            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", "", "", "", "", "", "", "", "", ""])

    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")
コード例 #16
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"
    # check Version NSX-T
    nsx_version = GetVersion(auth_list)

    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 version', nsx_version],
                 [
                     '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, 'B3:B5', 'STABLE')
    ConditionnalFormat(TN_WS, 'B6:B6', '3')
    ConditionnalFormat(TN_WS, 'B7:B7', '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)

    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",
                  "TableStyleLight9", False, startCell)
        ConditionnalFormat(TN_WS, 'G11:G' + str(len(XLS_Lines) + 1), 'UP')
        ConditionnalFormat(TN_WS, 'C11:C' + str(len(XLS_Lines) + 1), 'STABLE')
コード例 #17
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']
            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 = ('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')
コード例 #18
0
ファイル: docs_services.py プロジェクト: ysi/nsx-powerops
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")
コード例 #19
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)")

    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")
コード例 #20
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)

    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")
コード例 #21
0
ファイル: docs_lr_ports.py プロジェクト: ysi/nsx-powerops
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')