python - 如何使用boto3获取公共(public)IP

标签 python boto3

我需要从 AWS 中提取所有 RUNNING PUBLIC Ip,并且我正在使用以下代码:

def gather_public_ip():
    regions = ['us-west-2', 'eu-central-1', 'ap-southeast-1']
    combined_list = []   ##This needs to be returned
    for region in regions:
        instance_information = [] # I assume this is a list, not dict
        ip_dict = {}
        client = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY,
                              region_name=region, )
        instance_dict = client.describe_instances().get('Reservations')
        for reservation in instance_dict:
            for instance in reservation['Instances']: # This is rather not obvious
               if instance[unicode('State')][unicode('Name')] == 'running' and instance[unicode('PublicIpAddress')] != None:
                    ipaddress = instance[unicode('PublicIpAddress')]
                    tagValue = instance[unicode('Tags')][0][unicode('Value')] # 'Tags' is a list, took the first element, you might wanna switch this
                    zone = instance[unicode('Placement')][unicode('AvailabilityZone')]
                    info = ipaddress, tagValue, zone
                    instance_information.append(info)
        combined_list.append(instance_information)
    return combined_list

这对我不起作用,它给了我错误:
    ipaddress = instance[unicode('PublicIpAddress')]
KeyError: u'PublicIpAddress'

原因是PublicIpAddress在这个字典中不存在..有人可以帮我吗?

最佳答案

使用get()而不是 dict[key] . get()不会引发 KeyError .这里有一些例子可以解释。

>>> test = {'xxx':123}
>>> test['xxx']
123
>>> test['yyy']
KeyError: 'yyy'
>>> test.get('yyy')
>>> test.get('yyy') is None
True

您可以检查 'PublicIpAddress'缺席如下。
ipaddress = instance.get(u'PublicIpAddress')
if ipaddress is None:
   # Do Something

编辑
if instance[u'State'][u'Name'] == 'running' and instance.get(u'PublicIpAddress') is not None:
    print instance.get(u'PublicIpAddress')

关于python - 如何使用boto3获取公共(public)IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38049391/

相关文章:

python - 如何遍历 numpy 数组并删除异常?

python-3.x - 如何在不下载的情况下在 AWS S3 中列出 tar 中的文件?

python-3.x - boto3在设置IP地址时引用FEATURE_OCSP_MODE,但找不到相关文档

python - Pandas:在 DataFrame 中创建聚合列

python - BOTO3 DynamoDB 错误 : delete an item from a LIST attribute in a dynamodb table

python - 尝试使用执行 ID 检索对象时 AWS Athena python 连接 S3 错误

python - Boto3云信息错误: Template format error: unsupported structure

Python:从 csv 读取时间步长到数组:使用 numpy 后处理模型数据;

python - 如何更新QWidget的内容?

python - web2py:链接执行函数而不导航到不同的页面(回调?)