腾讯云python怎么用_Python操作腾讯云CVM

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

二、代码

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

三、测试

单独执行

bef2ab0dbbcdcd2b72294d957af4b70c.png

c9c05c92d911327eb712f09a33add85a.png

配合定时任务部署在服务器上

使用Python2.7 ,建议使用centos7以上不用单独安装python,默认版本即可操作

git clone https://github.com/redhatxl/my-python-code.git /usr/local/pythoncode

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

158059db44cfe201af052f24558270c3.png

查看日志

13c299206d8b604fa5652c441fbc49b1.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值