Boto3 - 打印 AWS 实例平均 CPU 利用率 [英] Boto3 - Print AWS Instance Average CPU Utilization

查看:52
本文介绍了Boto3 - 打印 AWS 实例平均 CPU 利用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅打印出 AWS 实例的平均 CPU 利用率.此代码将打印出响应",但最后的 for 循环不会打印平均利用率.有人可以帮忙吗?提前致谢!

I am trying to print out just the averaged CPU utilization of an AWS instance. This code will print out the 'response' but the for loop at the end isn't printing the averaged utilization. Could someone assist? Thank you in advance!

    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)

这是我收到的错误消息:

This is the error message I am getting:

    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

推荐答案

这将输出平均CPU:

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

这篇关于Boto3 - 打印 AWS 实例平均 CPU 利用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆