阿里云SDK-python控制ECS启动或关闭

python控制ECS启动或关闭

import sys
# from aliyunsdkcore import client
from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526 import StartInstanceRequest
from aliyunsdkecs.request.v20140526 import StopInstanceRequest
from datetime import datetime
import logging
 
logging.basicConfig(level=logging.DEBUG,
          format='%(asctime)s %(filename)s %(levelname)s %(message)s',
          datefmt='%a, %d %b %Y %H:%M:%S',
          filename='/tmp/aliyunhosts.log',
          filemode='w')
 
hostslist = ['i-bp15znfqmqlxuu20u0wv', 'i-bp15t830aynpq3q644ar', 'i-bp15t830aynpq3q644as']  # ['要启动的ecs id1','要启动的ecs id2','要启动的ecs id3'...]
clients = AcsClient('LdasdaTAdasdaI4GdddGern4QDUbzEbXXDpXy', '8qs4ztasd0Szz3ulpILAQ6pRSasddaXKpi3eHR', 'cn-hangzhou') # AcsClient('AccessKeyId','AccessKeySecret','地域名')
 
 
def ecsstart():
    for host in hostslist:
        try:
            start = StartInstanceRequest.StartInstanceRequest()
            start.set_InstanceId(host)
            action = clients.do_action_with_exception(start)
            # print("开始启动 " + host, action)
            logging.info("开始启动 " + host, action)
        except Exception as e:
            # print(e)
            print("实例 " + host, "已经启动!")
 
def ecsstop():
    try:
        for host in hostslist:
            stop = StopInstanceRequest.StopInstanceRequest()
            stop.set_InstanceId(host)
            action = clients.do_action_with_exception(stop)
            # print("开始关闭 " + host, action)
            logging.info("开始关闭 " + host, action)
    except Exception as e:
        # print(e)
        print("实例 " + host, "已经关机!")
 
if __name__ == "__main__":
    try:
        if sys.argv[1] == 'start':
            ecsstart()
        elif sys.argv[1] == 'stop':
            ecsstop()
        else:
            print("禁止瞎输入!")
    except Exception as e:
        print("start or stop")
posted @ 2021-05-30 14:08  SRE运维充电站  阅读(209)  评论(0编辑  收藏  举报