Python操作腾讯云CVM

栏目: Python · 发布时间: 8年前

内容简介:客户有需求在非工作时间将腾讯云CVM停机,工作时间又开起来,停止可以在系统内写定时任务来,但启动需要在腾讯云平台,就需要使用腾讯云的API来进行操作,还好腾讯云核心代码

一、背景

客户有需求在非工作时间将腾讯云CVM停机,工作时间又开起来,停止可以在系统内写定时任务来,但启动需要在腾讯云平台,就需要使用腾讯云的API来进行操作,还好腾讯云 SDK for Python ,简单记录下。

二、代码

git 地址

核心代码

  • CVM操作

    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

三、测试

  • 单独执行

    Python操作腾讯云CVM Python操作腾讯云CVM
  • 配合定时任务部署在服务器上
    使用 Python 2.7 ,建议使用centos7以上不用单独安装python,默认版本即可操作
    git clone https://github.com/redhatxl/my-python-code.git /usr/local/pythoncode

    配置好config.py中腾讯云平台的信息后(建议创建单个子用户,为子用户仅授权操作的cvm实例获取其secretid,secretkey),制作定时任务

    Python操作腾讯云CVM
  • 查看日志
    Python操作腾讯云CVM

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

中国制造2025:产业互联网开启新工业革命

中国制造2025:产业互联网开启新工业革命

夏妍娜、赵胜 / 机械工业出版社 / 2016-2-22 / 49.00

过去20年,是中国消费互联网肆意生长的"黄金20年",诞生了诸如BAT等互联网巨头,而时至今日,风口正逐渐转向了产业互联网。互联网这一摧枯拉朽的飓风,在改造了消费服务业之后,正快速而坚定地横扫工业领域,拉开了产业互联网"关键30年"的大幕。 "中国制造2025"规划,恰是中国政府在新一轮产业革命浪潮中做出的积极举措,是在"新常态"和"供给侧改革"的背景下,强调制造业在中国经济中的基础作用,认......一起来看看 《中国制造2025:产业互联网开启新工业革命》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具