前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >云服务器CVM批量关机脚本-Python

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

原创
作者头像
君的名字
修改2021-03-25 11:32:51
10.3K1
修改2021-03-25 11:32:51
举报
文章被收录于专栏:云API3.0最佳实践

通过此工具,你可以很方便的调用腾讯云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
Linux 下 pip 安装 Tencentcloud SDK
Windows 下 pip 安装 Tencentcloud SDK
Windows 下 pip 安装 Tencentcloud SDK

如何使用

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

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

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

密钥文件.txt
密钥文件.txt

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

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

IP地址.txt
IP地址.txt

⑤. 不同平台的运行方式

  • Windows

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

运行目录
运行目录

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

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

运行批量关机脚本
运行批量关机脚本

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

成功关机
成功关机
控制台显示成功关机
控制台显示成功关机

  • Linux

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

脚本文件所在目录
脚本文件所在目录

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

运行批量关机脚本
运行批量关机脚本

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

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

上代码!

代码语言:python
代码运行次数:0
复制
#! /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"""
输入 ./shutdown.py help 来查看如何使用此工具

关闭云服务器CVM的命令: ./shutdown.py shut <访问密钥,以Secretld 空格 SecreKey 的格式 保存文本即可> <需关机的云服务器IP地址 的格式 保存文本即可>

#温馨提示:此工具会在当前目录下生成关机操作的日志文件
"""
def cvm_shutdown(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.StopInstancesRequest()
        params = {
        "InstanceIds": [ str(InstanceId) ]
        # "ForceStop": True, 是否强制关机 此参数选填
        # "StopType": "SOFT_FIRST", 关闭实例的模式 此参数选填
        # "StoppedMode": "STOP_CHARGING" 是否开启关机不收费 此参数选填

        }

        req.from_json_string(json.dumps(params))

        resp = client.StopInstances(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] == 'shut':
			try:
				path = sys.argv[4]
			except Exception:
				path = str(os.path.dirname(os.path.abspath(__file__))) + "/shutdown_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_shutdown(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 删除。

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 通过此工具,你可以很方便的调用腾讯云API,对云服务器CVM进行关机的操作
    • 功能
      • 此工具的运行环境
        • 如何使用
          • 创建/获取密钥的链接:https://console.cloud.tencent.com/cam/capi
      • 上代码!
      相关产品与服务
      云服务器
      云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档