Python操做騰訊雲CVM

1、背景

客戶有需求在非工做時間將騰訊雲CVM停機,工做時間又開起來,中止能夠在系統內寫定時任務來,但啓動須要在騰訊雲平臺,就須要使用騰訊雲的API來進行操做,還好騰訊雲SDK for Python ,簡單記錄下。python

2、代碼

git 地址
核心代碼git

  • CVM操做github

    class CvmOper():
    def __init__(self,logger):
        config = configparser.ConfigParser()
        config.read('config.py',encoding='utf-8')
        self.instance_list = config['common']['InstanceIds'].split(',')
        print(self.instance_list)
        cred = credential.Credential(config['common']['SecretId'], config['common']['SecretKey'])
        self.clentoper = cvm_client.CvmClient(cred, config['common']['Region'])
    
        self.logger = logger
        self.logger.info("------------------------start cvm of API log-------------")
    def reboot_instance(self):
        """
        重啓cvm
        :return:
        """
        # 設置參數
        request = models.RebootInstancesRequest()
        request.InstanceIds=self.instance_list
        # 發起請求
        response = self.clentoper.RebootInstances(request)
        self.logger.info("public ecs *** reboot successful!")
        self.logger.info(response.to_json_string())
        print(response.to_json_string())
  • 配置文件
[common]
# 騰訊雲secretid
SecretId = AKIDjPYbTBU4FF4iAQuxxxxxxxxxxxxxxxxxxxxx
# 騰訊雲secretkey
SecretKey = e7RaXYVP63rUvBNUQxxxxxxxxxxxxxxxx
# cvm 所在地域
Region = ap-shanghai

# 騰訊雲cvm實例id,多個用,隔開
InstanceIds = ins-h8dxxxx
  • 日誌記錄
class CvmLog:
    def __init__(self,filename):
        self.filename = filename
    def createDir(self):
        _LOGDIR = os.path.join(os.path.dirname(__file__), 'cvmlog')
        print(_LOGDIR)
        _TIME = time.strftime('%Y-%m-%d', time.gmtime()) + '-'
        _LOGNAME = _TIME + self.filename
        print(_LOGNAME)
        LOGFILENAME = os.path.join(_LOGDIR, _LOGNAME)
        print(LOGFILENAME)
        if not os.path.exists(_LOGDIR):
            os.mkdir(_LOGDIR)
        return LOGFILENAME

    def createlogger(self,logfilename):
        logger= logging.getLogger()
        logger.setLevel(logging.INFO)
        handler = logging.FileHandler(logfilename)
        handler.setLevel(logging.INFO)
        formater = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formater)
        logger.addHandler(handler)
        return logger

3、測試

  • 單獨執行
    Python操做騰訊雲CVM
    Python操做騰訊雲CVMjson

  • 配合定時任務部署在服務器上
    使用Python2.7 ,建議使用centos7以上不用單獨安裝python,默認版本便可操做
    git clone https://github.com/redhatxl/my-python-code.git /usr/local/pythoncode

    配置好config.py中騰訊雲平臺的信息後(建議建立單個子用戶,爲子用戶僅受權操做的cvm實例獲取其secretid,secretkey),製做定時任務
    Python操做騰訊雲CVMcentos

  • 查看日誌
    Python操做騰訊雲CVM
相關文章
相關標籤/搜索