Python 来自子进程的 aws cli

Python aws cli from subprocess

import subprocess
import datetime

StartTime=datetime.datetime.utcnow() - datetime.timedelta(hours=1)
EndTime=datetime.datetime.utcnow()

instances = ['i-xxx1', 'i-xxx2']

list_files = subprocess.run(["aws", "cloudwatch", "get-metric-statistics", "--metric-name", "CPUUtilization", "--start-time", StartTime, "--end-time", EndTime, "--period", "300", "--namespace", "AWS/EC2", "--statistics", "Maximum", "--dimensions", "Name=InstanceId,#call the instances#"])
print("The exit code was: %d" % list_files.returncode)

快速而肮脏的代码。如何从实例列表中的 subprocess.run 循环并在循环中打印结果?从 StartTime 和 Endtime 格式调用日期时间也有问题。

谢谢

建议使用 boto3 库从 python 调用 AWS。将 cli 命令转换为 boto3 命令相当容易。

list_files = subprocess.run(["aws", "cloudwatch", "get-metric-statistics", "--metric-name", "CPUUtilization", "--start-time", StartTime, "--end-time", EndTime, "--period", "300", "--namespace", "AWS/EC2", "--statistics", "Maximum", "--dimensions", "Name=InstanceId,#call the instances#"])

您可以 运行 以下内容代替上述内容:

import boto3

client = boto3.client('cloudwatch')
list_files = client.get_metric_statistics(
    MetricName='CPUUtilization',
    StartTime=StartTime,  # These should be datetime objects
    EndTime=EndTime,  # These should be datetime objects
    Period=300,
    Namespace='AWS/EC2',
    Statistics=['Maximum'],
    Dimensions=[
        {
            'Name': 'InstanceId',
            'Value': '#call the instances#'
        }
    ]

您可以运行 help(client.get_metric_statistics) 获取有关该功能的详细信息。 boto3 库有很好的文档记录。响应结构和语法也记录在那里。