Boto3 - 打印AWS实例平均CPU利用率

时间:2018-04-26 13:50:34

标签: python amazon-web-services amazon-ec2 boto3

我正在尝试打印出AWS实例的平均CPU利用率。此代码将打印出“回复”#39;但最后的for循环不打印平均利用率。有人可以协助吗?提前谢谢!

    import boto3
    import sys
    from datetime import datetime, timedelta
        client = boto3.client('cloudwatch')
        response = client.get_metric_statistics(
            Namespace='AWS/EC2',
            MetricName='CPUUtilization',
            Dimensions=[
                {
                'Name': 'InstanceId',
                'Value': 'i-1234abcd'
                },
            ],
            StartTime=datetime(2018, 4, 23) - timedelta(seconds=600),
            EndTime=datetime(2018, 4, 24),
            Period=86400,
            Statistics=[
                'Average',
            ],
            Unit='Percent'
        )
    for cpu in response:
        if cpu['Key'] == 'Average':
            k = cpu['Value']
    print(k)

这是我收到的错误消息:

    Traceback (most recent call last):
      File "C:\bin\TestCW-CPU.py", line 25, in <module>
        if cpu['Key'] == 'Average':
    TypeError: string indices must be integers

2 个答案:

答案 0 :(得分:2)

for cpu in response['Datapoints']:
  if 'Average' in cpu:
    print(cpu['Average'])

2.25348611111
2.26613194444

如果你打印了cpu

的值,你可以很容易地想出来
print(response)

for cpu in response['Datapoints']:
  print(cpu)

{u'Timestamp': datetime.datetime(2018, 4, 23, 23, 50, tzinfo=tzlocal()), u'Average': 2.2534861111111106, u'Unit': 'Percent'}
{u'Timestamp': datetime.datetime(2018, 4, 22, 23, 50, tzinfo=tzlocal()), u'Average': 2.266131944444444, u'Unit': 'Percent'}

答案 1 :(得分:0)

这将输出平均CPU:

    for k, v in response.items():
        if k == 'Datapoints':
        for y in v:
            print(y['Average'])