Python批量开关EC2脚本

前提条件:

  • 需要本机配置AWS CLI的AK/SK;
  • 本机安装Python3;
  • 本机安装boto3库(执行pip3 install boto3)。

Python脚本如下:

import boto3.ec2
client = boto3.client('ec2')
ec2action = boto3.resource('ec2')

response = client.describe_instance_status(
    IncludeAllInstances=True
)

for i in response['InstanceStatuses']:
    instance = ec2action.Instance(i['InstanceId'])
    response1 = instance.stop(
            #DryRun=True,
            Force=True
    )
    print("instance: ", i['InstanceId'], "is being stopped." )
    print(response1)

以上为关机脚本。如果需要批量开机,替换stop为start即可。