如何使用 Python 检索 AWS Lambda public IP 地址?

How could I retrieve AWS Lambda public IP address by using Python?

我的应用是使用link(url)来调用lambda函数,然后我想知道public lambda的IP并获取页面源。如何使用 python 获取 lambda public IP? 非常感谢。

您可以 curl 到 checkip.amazonaws.com 以获得 public IP。

import requests
requests.get('http://checkip.amazonaws.com').text.rstrip()

输出:

52.x.147.64

我建议:

from botocore.vendored import requests
requests.get('http://checkip.amazonaws.com').text.rstrip()

在您的 lambda 函数中。

否则,您可能会收到一条错误消息,指出 lambda 无法找到 requests,除非您从包含通过 pip[=15= 安装的 requests 的 .zip 文件创建了 lambda ]

import urllib3
http = urllib3.PoolManager()
response = http.request('GET', 'http://checkip.amazonaws.com')
response.__dict__

IP 地址在 '_body' 属性中找到。

替代解决方案由于:

  1. 无法使用 requests 因为它不是核心的一部分
  2. 发现 AWS 删除的 botocore 销售版本 here

您可以使用不需要 pip 的 urllib 而不是 import requests

示例代码如下;


from urllib.request import Request, urlopen


def lambda_handler(event, context):
    url = 'http://checkip.amazonaws.com'
    with urlopen(Request(url)) as response:
        print(response.read().decode('utf-8'))