学习
实践
活动
专区
工具
TVP
写文章
专栏首页云API3.0最佳实践云服务器CVM批量开机脚本-Python
原创

云服务器CVM批量开机脚本-Python

通过此工具,你可以很方便的调用腾讯云API,对云服务器CVM进行开机的操作


功能

①.结合云服务器CVM批量关机脚本 | 实现定时开关云服务器的功能 √

②.自动化运维 √

③.待你发现 🙃


此工具的运行环境

①.Linux或者Windows系统

②.Python 2.7.9

>>点我下载 https://www.python.org/downloads/release/python-279/

③.安装 TencentCloud Python SDK

bash 或者 cmd 中运行 pip install tencentcloud-sdk-python

Linux 下 pip 安装 Tencentcloud SDK

Windows 下 pip 安装 Tencentcloud SDK


如何使用

①.安装Python 2.7.9环境 (若是Centos7,默认已带此环境)

②.安装pip 以及 使用pip下载安装 tencentcloud-sdk-python

③.将密钥保存在txt文件中(文件名可自定义),如下图所示

密钥文件.txt

创建/获取密钥的链接:https://console.cloud.tencent.com/cam/capi

④.将需要进行关机的云服务器CVM 公网IP地址保存在txt文件中(一行一个IP,文件名可自定义),如下图所示

IP地址.txt

⑤. 不同平台的运行方式

  • Windows

将 start.py、密钥文件、云服务器CVM的IP地址 放在同一目录下

脚本文件所在目录

在此目录下打开cmd或者powershell或者cmder

输入 python start.py start key.txt instance.txt 并且回车运行

运行批量开机脚本

等待10-15s,出现开机成功的提示即可

成功开机
控制台显示成功启动实例

  • Linux

与Windows类似,将 shutdown.py、密钥文件、云服务器CVM的IP地址 放在同一目录下

开机脚本文件所在目录

在终端中 输入 python start.py start key.txt instance.txt 并且回车运行

运行批量开机脚本

等待10-15s,出现关机成功的提示即可

成功开机
控制台显示成功批量开机

上代码!

#! /usr/bin/env python
# -*- coding: utf-8 -*-

# 本工具主要功能:批量启动云服务器CVM

# region的地域列表:https://cloud.tencent.com/document/api/214/30670#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8

import json, sys ,os, time, datetime
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models

reload(sys)
sys.setdefaultencoding("utf-8")

now= str(datetime.datetime.now().strftime("%Y 年 %m 月 %d 日  -  %H:%M:%S"))
all_region = ['ap-bangkok','ap-beijing','ap-chengdu','ap-chongqing','ap-guangzhou','ap-hongkong','ap-mumbai',
          'ap-nanjing','ap-seoul','ap-shanghai','ap-shanghai-fsi','ap-shenzhen-fsi','ap-singapore',
          'ap-tokyo','eu-frankfurt','eu-moscow','na-ashburn','na-siliconvalley','na-toronto']

def print_help():
    print"""
输入 ./start.py help 来查看如何使用此工具

重装系统的命令: ./start.py start <访问密钥,以Secretld 空格 SecreKey 的格式 保存文本即可> <需开机的云服务器CVM IP地址 的格式 保存文本即可>

#温馨提示:此工具会生成云服务器开机操作的日志文件
"""

def cvm_start(Secretld,SecreKey,region,InstanceId):

    try:
        cred = credential.Credential(SecretId,SecretKey) 
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(cred, region, clientProfile) 

        req = models.StartInstancesRequest()
        params = {
        "InstanceIds": [ str(InstanceId) ]
        }

        req.from_json_string(json.dumps(params))

        resp = client.StartInstances(req)
        return resp.to_json_string()

    except TencentCloudSDKException as err: 
        return err

def _ID_region_from_eip(SecretId,SecretKey,region,offset):

	try:
		cred = credential.Credential(SecretId, SecretKey)
		httpProfile = HttpProfile()
		httpProfile.endpoint = "cvm.tencentcloudapi.com"

		clientProfile = ClientProfile()
		clientProfile.httpProfile = httpProfile
		client = cvm_client.CvmClient(cred, region, clientProfile)

		req = models.DescribeInstancesRequest()
		params = {
			"Limit": 20,
			"Offset": offset
		}
		req.from_json_string(json.dumps(params))

		resp = client.DescribeInstances(req)
		return resp.to_json_string()

	except TencentCloudSDKException as err:
		return err

def log_log(log_content, path):
	
	print "\033[0;31m 本工具最近一次运行的时间: "+now +'\033[0m \n\n'
	
	fin=open(path,'a') # 追加原始内容的写入
	content = log_content + "\033[0;31m 本工具最近一次运行的时间: "+now +'\033[0m \n\n'
	fin.write(content)
	fin.close()

if __name__ == '__main__':
	try:
		if_sys_argv_exit = sys.argv[1]
	except Exception:
		print_help()
		exit()

	if sys.argv[1] == 'help':
		print_help()
		exit()

	else:
		font = open('%s'%sys.argv[2])
		font = font.readline()
		token = font.split()
		SecretId = token[0]
		SecretKey = token[1]

		if sys.argv[1] == 'start':
			try:
				path = sys.argv[4]
			except Exception:
				path = str(os.path.dirname(os.path.abspath(__file__))) + "/start_cvm.log"

			content = ''
			ip_dict={ }

			for city in all_region:
				result = _ID_region_from_eip(SecretId,SecretKey,city,0)

				try:
					result_dict = json.loads(result)
				except Exception:
					print result
					print "because of above reason, this tool is crashed, please try later"
					content += str(result) +'\n'
					content += "because of above reason, this tool is crashed, please try later"
					log_log(content,path)
					exit()

				TotalCount = result_dict['TotalCount'] #本次查询到了多少CVM

				left_times = TotalCount/20 + 1
				offset = 0

				while left_times>0:
					result = _ID_region_from_eip(SecretId,SecretKey,city,offset)
					try:
						result_dict = json.loads(result)
					except Exception:
						print result
						print "because of above reason, this tool is crashed, please try later"
						content += str(result) + '\n'
						content += "because of above reason, this tool is crashed, please try later"
						log_log(content,path)
						exit()


					for i in result_dict['InstanceSet']:
						InstanceId = i['InstanceId']

						try:
							TF_eip = i['PublicIpAddresses'][0]
						except Exception:
							continue

						for j_ip in i['PublicIpAddresses']:
							eip = j_ip
							ip_dict[eip] = [ InstanceId  , city ]

					left_times -= 1
					offset += 20

			#print ip_dict

			fout=open('%s'%sys.argv[3])
			while 1:
				time.sleep(0.12)
				line = fout.readline()
				if not line :
					break

				line  = line.strip()
				try:
					top_word = line[0]
				except Exception:
					continue

				if top_word=='#':
					continue

				all_conf = line.split()
				ip = all_conf[0]

				if '.' not in all_conf[0]:
					print line + ' 当前帐号下找不到该服务器 '
					print ' '
					content += line + ' 当前帐号下找不到该服务器 查询时间: ' + now + '\n\n'
					continue

				if ip not in ip_dict:
					print line + ' 当前帐号下找不到该服务器 '
					print ' '
					content +=  line + ' 当前帐号下找不到该服务器 查询时间: '+ now + '\n\n'
					continue

				result = cvm_start(SecretId,SecretKey,region=ip_dict[ip][1],InstanceId=ip_dict[ip][0])

				try:
					result_dict = json.loads(result)
					RequestId = result_dict['RequestId']
					print ' 云服务器IP ' + line + ' ' + ip_dict[ip][1] + ' 地域下 ' + ' 实例ID为 '+ ip_dict[ip][0] + ' 的云服务器开机成功 '
					print ' '
					content += ' 云服务器IP ' + line + ' ' + ip_dict[ip][1] + ' 地域下 ' + ' 实例ID为 '+ ip_dict[ip][0] + ' 的云服务器在 ' + now + ' 点 开机成功' + '\n\n'
					
				except Exception:
					print line + ' '+ip_dict[ip][0]+' '+ip_dict[ip][1]+ ' is fail '
					print result
					print ' '
					content +=  line + ' '+ip_dict[ip][0]+' '+ip_dict[ip][1]+ ' is fail time:' + now + '\n' + str(result) + '\n\n'
					
			log_log(content,path)
		else:
			print '\n'
			print ' 当前目录下没有找到这个 %s ' % sys.argv[1] + ' 这个文件 '
			print '\n'
			print_help()

原创声明,本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

登录 后参与评论
0 条评论

相关文章

  • 云服务器CVM批量关机脚本-Python

    >>点我下载 https://www.python.org/downloads/release/python-279/

    君的名字
  • 基础网络CVM使用API批量切换私有网络/批量回退基础网络

    vic@TX
  • 部署云服务器--(3) Linux系统用脚本方式实现Tomcat的开机自启动

    此篇教程在我的电脑(deepin-generic)上是可以用的,做好脚本后重启立即生效,但是在服务器(CentOS-7.3),需要开机后等待十几分钟,原因不明...

    浩Coding
  • 腾讯开源|TAT Agent-助力轻松完成云服务器运维管理任务

    1、项目简介 腾讯云自动化助手 TAT 是云服务器的原生运维部署工具,可以远程执行 Shell、PowerShell、Python 等脚本。TAT Agent...

    腾讯开源
  • 利用Python调用云Api实现批量共享云服务器自定义镜像

    请注意 为了保障您的账户以及云上资产的安全 请谨慎保管SecretId 与 SecretKey 并定期更新 删除无用权限

    小宇-xiaoyu
  • 主机迁移实践分享

    在云计算时代,不管是从IDC上云还是多云直接的迁移,都已经是常见的事宜。而在上云/迁移的方案中,也是有多种的方式能够将主机迁移到腾讯云中。

    腾讯云计算产品团队
  • 【玩转腾讯云】Serverless+CVM实战

    写过一篇Serverless初探,后期结合Tencent Serverless Toolkit for VS Code的IDE插件,刚好借此使用下,相较于之前没...

    KaliArch
  • 腾讯云 API 3.0实践分享(下)

    当前腾讯云的产品的 API 陆陆续续都在切换到 3.0了,为了帮助用户快速掌握 API 3.0的用法,上周分享了《腾讯云 API 3.0实践分享》一文,不少用户...

    腾讯云计算产品团队
  • 【转】腾讯云 API 3.0实践分享(下)

    原文地址:https://cloud.tencent.com/developer/article/1155254

    None-xiaomi
  • 再见云服务器!教你将 Python 脚本快速部署在手机上(详细)

    最近有读者后台给我留言,说这段时间云服务器涨价了,自己日常就运行一些简单的脚本,因此不太想入坑云服务器,问我能不能提供一个不一样的思路给他

    AirPython
  • 利用Python调用云Api批量修改轻量应用服务器名称

    请注意 为了保障您的账户以及云上资产的安全 请谨慎保管SecretId 与 SecretKey 并定期更新 删除无用权限

    小宇-xiaoyu
  • TBase分布式数据的安装部署

    本次实验是基于腾讯CVM(腾讯云虚拟主机)部署的TBase企业版集群,需要部署开源版集群的请移步开源部署方案

    用户7689089
  • TKE操作笔记02

    本次笔记主要讲述了如何在腾讯云控制台创建并使用你的第一个kubernetes集群,创建过程中每个步骤的区别以及如何选择,保证自己的集群资源达到最优。

    聂伟星
  • TKE操作指南 - 创建TKE CVM容器集群(八)

    现在跳转到了私有网络创建界面,由于容器集群网络只支持私有网络,点击现在新建(容器集群网络只支持私有网络),输出私有网络名称(fengliang-vpc),和子网...

    亮哥说TKE
  • 腾讯云 CVM 入门

    腾讯云目前支持三种不同的方式来登录和管理您的 CVM, 请您根据自身场景灵活选择登录方式:控制台,CLI 和 API/SDKs。

    勤劳的小蜜蜂
  • 利用Python调用云Api实现批量绑定轻量应用服务器密钥

    请注意 为了保障您的账户以及云上资产的安全 请谨慎保管SecretId 与 SecretKey 并定期更新 删除无用权限

    小宇-xiaoyu

扫码关注腾讯云开发者

领取腾讯云代金券