跳至內容

如何識別、監控和最佳化 Amazon VPC 公共 IPv4 位址使用情況?

4 分的閱讀內容
0

我想識別、監控和最佳化 Amazon Virtual Private Cloud (Amazon VPC) IPv4 位址使用情況。

解決方法

**注意:**如果您在執行 AWS Command Line Interface (AWS CLI) 命令時收到錯誤訊息,請參閱對 AWS CLI 錯誤進行疑難排解。此外,請確定您使用的是最新的 AWS CLI 版本

所有公共 IPv4 位址,無論是否連接到服務,每個 IP 位址每小時均需支付 0.005 美元的費用。如果您是 Amazon Elastic Compute Cloud (Amazon EC2) 的 AWS 免費方案客戶,您將獲得 750 小時的免費使用時間。當您啟動具有公共 IPv4 位址的 Amazon EC2 執行個體時,即可免費使用。

啟用公共 IP 洞察功能

您可以使用公共 IP 洞察功能來監控、分析和稽核您的服務目前在 AWS 區域中使用的公共 IPv4 位址。

若要啟用公共 IP 洞察功能,請建立 Amazon VPC IP 位址管理器 (IPAM) 集區。若要識別公共 IPv4 位址的使用情況,請將 IPAM 公共 IP 洞察功能單一 AWS 帳戶或您的 AWS Organizations 帳戶整合。

注意:免費方案下的公共 IP 洞察功能是免費的。如需進階層的定價資訊,請參閱 Amazon VPC 定價頁面上的 IPAM 索引標籤。當您將 IPAM 與 Organizations 整合時,即使在免費方案中,也能對您組織中的所有區域和帳戶使用公共 IP 洞察功能

若要查看結果,您可以使用 Amazon VPC 主控台或 AWS CLI。

**注意:**建立 IPAM 集區後,公共 IP 洞察功能會產生您公共 IPv4 位址的報告。產生報告所需的時間取決於您組織的規模。

啟用您的 Cost and Usage Report

您的 AWS Cost and Usage Report (CUR) 包括已使用和未使用的公共 IPv4 位址使用情況資料。當您建立 CUR 時,請選取 Include resource IDs (包含資源 ID) 以獲得詳細的資源層級分析。建立 CUR 後,AWS 會每天至少更新一次包含當月資料的報告檔案。您可以使用報告檔案來分析歷史 IPv4 位址使用情況資料。

**注意:**您可以從 Amazon Simple Storage Service (Amazon S3) 儲存貯體存取報告。AWS 可能需要長達 24 小時才能將報告傳送到您的 Amazon S3 儲存貯體。

立即識別公共 IPv4 位址

注意:最佳實務是使用 CUR 和公共 IP 洞察功能來依計劃分析公共 IPv4 位址的使用情況。

若要立即識別使用公共 IPv4 位址的服務,請使用 Amazon EC2 主控台或 AWS CLI。

Amazon EC2 主控台

若要分析您的網路介面以檢視使用公共 IPv4 位址的 AWS 服務,請完成下列步驟:

  1. 開啟 Amazon EC2 console (Amazon EC2 主控台)。
  2. 在導覽窗格中的 Network & Security (網路與安全性) 下,選擇 Network Interfaces (網路介面)。
  3. Public IPv4 Addresses (公共 IPv4 位址) 篩選器下,輸入 <*> 以識別使用主要公共 IPv4 位址的彈性網路介面。
  4. 使用網路介面描述和介面類型來識別使用公共 IPv4 位址的服務。
  5. 若要顯示區域中具有網路介面的所有公共和次要 IP 位址,請執行下列命令:
    aws ec2 describe-network-interfaces --region example-region --query 'NetworkInterfaces[*].PrivateIpAddresses[?Association.PublicIp].Association.PublicIp[]' --output table
    **注意:**將 example-region 替換為您的區域。

如需 AWS Site-to-Site VPN 使用的公共 IPv4 位址,請參閱如何檢查 VPN 通道的目前狀態?

如需標準和自訂 AWS Global Accelerator 的公共 IPv4 位址,請參閱查看您的加速器

若要查看閒置或關聯的彈性 IP 位址,請完成下列步驟:

  1. 開啟 Amazon EC2 console (Amazon EC2 主控台)。
  2. 在導覽窗格中的 Network & Security (網路與安全性) 下,選擇 Elastic IPs (彈性 IP)。
  3. 選取一個彈性 IP 位址,查看使用該彈性 IP 位址的資源。
    **注意:**如需使用情況的詳細資訊,請檢查 Network interface (網路介面) 或 Instance (執行個體) 欄位。

自備 IP 位址 (BYOIP) 不會收取任何費用。AWS 會在 us-west-2 區域對 Global Accelerator 進行計費。

AWS CLI

**先決條件:**執行 aws configure AWS CLI 命令來設定您的憑證。另外,請安裝 Boto3。如需詳細資訊,請參閱 Boto3 網站上的安裝 Boto3

若要立即識別使用公共 IPv4 位址的服務,請從 AWS CloudShell 或 Linux 環境完成下列步驟:

  1. 建立以下檔案:

    touch public_ipv4_recon.py
  2. 執行以下命令來編輯檔案:

    vim public_ipv4_recon.py
  3. 將以下程式碼複製並貼上到檔案中,然後儲存檔案:

    #!/usr/bin/env python3
    import pprint
    import boto3, sys
    
    profile = boto3.Session(profile_name=sys.argv[1])
    aga = profile.client('globalaccelerator', region_name='us-west-2')
    ec2 = boto3.client('ec2')
    
    def global_public_ipv4_lookup(aga):
      try:
        # global accelerator
        next_token = None
        while True:
          if next_token:
            resource = aga.list_accelerators(
            NextToken = next_token
              )
          else:
            resource = aga.list_accelerators(
            )
          print('Describing world wide Global Accelerators...')
          print('Note: AWS Global Accelerators are billed in us-west-2....')
          print(f'Number of AGA: {len(resource["Accelerators"])}')
          print('-'*40)
          for item in resource["Accelerators"]:
            print(f'Name: {item["Name"]}')
            if 'IpSets' in item.keys():
              for ip in item["IpSets"][0]["IpAddresses"]:
                print(f'Public IPv4: {ip}')
            print(f'Status: {item["Status"]}')
            print()
          next_token = resource.get("NextToken")
          if next_token is None:
            break
        print()
        # custom_routing_accelerators
        next_token = None
        while True:
          if next_token:
            custom_routing = aga.list_custom_routing_accelerators(
              NextToken = next_token
            )
          else:
            custom_routing = aga.list_custom_routing_accelerators(
            )
          print('Describing world wide Custom Routing Accelerators...')
          print('Note: AWS Global Accelerators are billed in us-west-2....')
          print(f'Number of custom AGA: {len(custom_routing["Accelerators"])}')
          print('-'*40)
          for item in custom_routing["Accelerators"]:
            if 'IpSets' in item.keys():
              for ip in item["IpSets"][0]["IpAddresses"]:
                print(f'Public IPv4: {ip}')
            print(f'Status: {item["Status"]}')
            print()
          next_token = custom_routing.get("NextToken")
          if next_token is None:
            break
        print()
      except Exception as err:
        print(f'Error found: {err}...')
        pass
    
    def public_ipv4_lookup(ec2):
      try:
        # vpn
        next_token = None
        while True:
          if next_token:
            vpn = ec2.describe_vpn_connections(
                  NextToken = next_token
            )
          else:
            vpn = ec2.describe_vpn_connections(
            )
          print('Describing VPNs...')
          print(f'Number of Vpn connections: {len(vpn["VpnConnections"])}')
          print('-'*40)
          for item in vpn["VpnConnections"]:
            if 'VpnConnectionId' in item.keys():
              print(f'Vpn Id: {item["VpnConnectionId"]}')
              for ip in item["VgwTelemetry"]:
                print(f'Public ipv4: {ip["OutsideIpAddress"]}')
            print()
          next_token = vpn.get("NextToken")
          if next_token is None:
            break
        print()
        # elastic ip
        eip = ec2.describe_addresses(
        )
        print('Describing Elastic IPs...')
        print(f'Number of Elastic Ips: {len(eip["Addresses"])}')
        print('-'*40)
        for item in eip["Addresses"]:
          if 'AllocationId' in item.keys():
            print(f'Eip Id: {item["AllocationId"]}')
            print(f'Public ipv4: {item["PublicIp"]}')
            print()
        print()
        # network interfaces
        next_token = None
        while True:
          if next_token:
            interface = ec2.describe_network_interfaces(
            NextToken=next_token
              )
          else:
            interface = ec2.describe_network_interfaces(
            )
          print('Describing Network Interfaces...')
          print(f'Number of interfaces: {len(interface["NetworkInterfaces"])}')
          print('Only printing Interfaces with a public IPv4 address...')
          print('-'*40)
          for item in interface["NetworkInterfaces"]:
            for ip in item["PrivateIpAddresses"]:
              if 'Association' not in ip.keys():
                pass
              else:
                print(f'Interface Id: {item["NetworkInterfaceId"]}')
                print(f'Description: {item["Description"]}')
                print(f'Status: {interface["NetworkInterfaces"][0]["Status"]}')
                print(f'Public Ip: {ip["Association"]["PublicIp"]}\n')
          next_token = interface.get("NextToken")
          if next_token is None:
            break
      except Exception as err:
        print(f'Error found: {err}...')
        pass
    
    # Run code
    if len(sys.argv) < 3 or not sys.argv[2]:
      global_public_ipv4_lookup(aga)
      regions_list = ec2.describe_regions(
          AllRegions=False
      )
      for region in regions_list['Regions']:
        if region["OptInStatus"] == 'opted-in' or 'opt-in-not-required':
          print(f'\n**********-[{region["RegionName"]}]-**********\n')
          public_ipv4_lookup(
            ec2=profile.client('ec2', region_name=region["RegionName"])
            )
    elif sys.argv[2]:
      global_public_ipv4_lookup(aga)
      public_ipv4_lookup(
        ec2=profile.client('ec2', region_name=sys.argv[2])
        )
  4. 若要檢查所有區域,請執行以下命令:

    python3 public_ipv4_recon.py example-cli-profile

    **注意:**將 example-cli-profile 替換為已設定的 AWS CLI 設定檔名稱,或 .aws/credentials 檔案中定義的任何設定檔名稱。如果您使用的是 Windows,請將 python3 替換為 python
    -或-
    若要檢查特定區域,請執行以下命令:

    python3 public_ipv4_recon.py example-cli-profile example-region

    **注意:**將 example-cli-profile 替換為已設定的 AWS CLI 設定檔名稱,或 .aws/credentials 檔案中定義的任何設定檔名稱。將 example-region 替換為對應區域。

如果您無權執行該請求或該區域已停用您的帳戶,那麼您可能會收到以下錯誤:

"Error found: An error occurred (AuthFailure) when calling the <API> operation: AWS was not able to validate the provided access credentials..."

最佳化公共 IPv4 位址使用情況,並採用 IPv6 位址

若要最佳化成本,請增強您目前的架構,以將公共 IPv4 位址的使用降至最低。最佳實務是遷移到 IPv6。IPv6 位址是免費的。

AWS 官方已更新 7 個月前