Skip to main content
 首页 » 编程设计

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

2024年09月07日11artech

我正在尝试仅打印出 AWS 实例的平均 CPU 利用率。此代码将打印出“响应”,但末尾的 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 

请您参考如下方法:

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'}