来自子流程的python aws cli

tzxcd3kk  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(365)
  1. import subprocess
  2. import datetime
  3. StartTime=datetime.datetime.utcnow() - datetime.timedelta(hours=1)
  4. EndTime=datetime.datetime.utcnow()
  5. instances = ['i-xxx1', 'i-xxx2']
  6. 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#"])
  7. print("The exit code was: %d" % list_files.returncode)

快速而肮脏的代码。如何从subprocess.runfrom instances列表循环并在循环中打印结果?从starttime和endtime格式调用datetime时也有问题。
非常感谢。

wwwo4jvm

wwwo4jvm1#

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

  1. 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#"])

您可以运行以下操作,而不是上述操作:

  1. import boto3
  2. client = boto3.client('cloudwatch')
  3. list_files = client.get_metric_statistics(
  4. MetricName='CPUUtilization',
  5. StartTime=StartTime, # These should be datetime objects
  6. EndTime=EndTime, # These should be datetime objects
  7. Period=300,
  8. Namespace='AWS/EC2',
  9. Statistics=['Maximum'],
  10. Dimensions=[
  11. {
  12. 'Name': 'InstanceId',
  13. 'Value': '#call the instances#'
  14. }
  15. ]

你可以跑 help(client.get_metric_statistics) 获取有关函数的详细信息。这个 boto3 这个图书馆有很好的文档记录。响应结构和语法也记录在那里。

展开查看全部

相关问题