来自子流程的python aws cli

tzxcd3kk  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(349)
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.runfrom instances列表循环并在循环中打印结果?从starttime和endtime格式调用datetime时也有问题。
非常感谢。

wwwo4jvm

wwwo4jvm1#

建议使用 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 这个图书馆有很好的文档记录。响应结构和语法也记录在那里。

相关问题