跳至内容

如何识别、监控和优化我的 Amazon VPC 公共 IPv4 地址使用情况?

4 分钟阅读
0

我想识别、监控和优化我的 Amazon Virtual Private Cloud (Amazon VPC) IPv4 地址使用情况。

解决方案

**注意:**如果您在运行 AWS 命令行界面 (AWS CLI) 命令时收到错误,请参阅 AWS CLI 错误故障排除。此外,请确保您使用的是最新版本的 AWS CLI

所有公共 IPv4 地址每个地址每小时将产生 0.005 美元的费用,无论是否已关联到某项服务。如果您是 Amazon Elastic Compute Cloud (Amazon EC2) 的 AWS Free Tier 客户,您将获得 750 小时的免费使用时间。此免费使用时间适用于启动具有公共 IPv4 地址的 Amazon EC2 实例。

激活公共 IP 洞察功能

您可以使用公共 IP 洞察功能来监控、分析和审计您的服务目前在 AWS 区域中使用的公共 IPv4 地址。

要激活公共 IP 洞察功能,请创建 Amazon VPC IP 地址管理器 (IPAM) 池。要确定公共 IPv4 地址的使用情况,请将 IPAM 公共 IP 洞察功能集成到单个 AWS 账户或您的 AWS Organizations 账户

注意:Free Tier 下的 Public IP insights(公共 IP 洞察功能)是免费的。有关 Advanced Tier 定价信息,请参阅 Amazon VPC 定价页面上的 IPAM 选项卡。当您将 IPAM 与 Organizations 集成时,您可以将公共 IP 洞察功能用于组织中的所有区域和账户,即使是 Free Tier 也是如此。

查看结果,您可以使用 Amazon VPC 控制台或 AWS CLI。

**注意:**创建 IPAM 池后,公共 IP 洞察功能会为您的公共 IPv4 地址生成一份报告。生成报告所需的时间取决于您的组织规模。

启用您的成本和使用情况报告

您的 AWS 成本和使用情况报告 (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 地址的服务,请完成以下步骤:

  1. 打开 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 控制台
  2. 在导航窗格中的 Network & Security(网络和安全)下,选择 Elastic IPs(弹性 IP)。
  3. 选择弹性 IP 地址以查看使用该弹性 IP 地址的资源。
    **注意:**有关使用情况的详细信息,请查看 Network interface(网络接口)或 Instance(实例)字段。

自带 IP 地址 (BYOIP) 不产生任何费用。AWS 向 us-west-2 区域的全球加速器开具账单。

AWS CLI

**先决条件:**运行 aws configure AWS CLI 命令以设置您的凭证。另外,安装 Boto3。有关详细信息,请参阅 Boto3 网站上的 Install 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 官方已更新 4 个月前