云服务器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()
本站文章资源均来源自网络,除非特别声明,否则均不代表站方观点,并仅供查阅,不作为任何参考依据!
如有侵权请及时跟我们联系,本站将及时删除!
如遇版权问题,请查看 本站版权声明
THE END
分享
二维码
海报
云服务器CVM批量开机脚本-Python
>>点我下载 https://www.python.org/downloads/release/python-279/
<<上一篇
下一篇>>