Authored by root

Add auto decommission

... ... @@ -28,7 +28,7 @@ class QcloudApi:
self.secretId = secretId
self.secretKey = secretKey
def do_query(self, params, req_url=URLS_lb):
def do_query(self, params, req_url=URLS_lb, api_version=2):
"""
Do Query Qcloud api
:param params: 查询参数,dict类型,必须包含 Action
... ... @@ -39,15 +39,26 @@ class QcloudApi:
print("must provide [Action] params !")
raise ValueError(params)
public_params = {'RequestClient': QcloudApi.Version, 'limit': 100, 'Region': QcloudApi.Region, 'Timestamp': int(time.time()), 'Nonce': QcloudApi.generate_nonce(), 'SecretId': self.secretId}
# merge params
params = dict(params, **public_params)
# signature
sign = self.signature(params, req_url)
params['Signature'] = sign
response_dict = requests.post("https://" + req_url, data=params).json()
if api_version == 2:
public_params = {'RequestClient': QcloudApi.Version, 'limit': 100, 'Region': QcloudApi.Region, 'Timestamp': int(time.time()), 'Nonce': QcloudApi.generate_nonce(), 'SecretId': self.secretId}
# merge params
params = dict(params, **public_params)
# signature
sign = self.signature(params, req_url)
params['Signature'] = sign
response_dict = requests.post("https://" + req_url, data=params).json()
elif api_version == 3:
public_params = {'Region': QcloudApi.Region, 'Timestamp': int(time.time()), 'Nonce': QcloudApi.generate_nonce(), 'Version': '2017-03-12', 'SecretId': self.secretId, 'SignatureMethod':'HmacSHA1'}
# merge params
params = dict(params, **public_params)
# signature
req_url = req_url.rstrip('/')+'/'
sign = self.signature(params, req_url)
params['Signature'] = sign
response_dict = requests.post("https://" + req_url, data=params).json()
print("call qcloud api success. params:\n %s \n" % (params))
print json.dumps(response_dict, indent=4, sort_keys=True)
#print json.dumps(response_dict, indent=4, sort_keys=True)
return response_dict
@staticmethod
... ... @@ -67,6 +78,7 @@ class QcloudApi:
kv_pairs.append('%s=%s' % (key, request_params[key]))
str_req = '&'.join(kv_pairs)
str_full = 'POST%s?%s' % (url, str_req)
print 'str_full',str_full
hmac_sign = hmac.new(bytes(self.secretKey), bytes(str_full), hashlib.sha1).digest()
return base64.b64encode(hmac_sign).decode()
... ...
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author tiexin.yang@yoho.cn
from qcloud.qcloud_api import QcloudApi
from qcloud.mailer import mailman
from zabbix import delete_host_by_ip
import datetime
import argparse
import os,shutil
import sys
import time
import json
import re
"""
作用:通过制定ip销毁,退还按需/按量付费类型势力,同时注销zabbix host
依赖:zabbix.py(注销zabbix host)
Demo:
python server_decomission.py 1.2.3.4
"""
class consoleRobot(object):
def __init__(self,secretId='',secretKey=''):
if not secretId or not secretKey:
self.secretId,self.secretKey = open('/home/ansible/.qcloud_config').read().strip('\n').split('\n')
else:
self.secretId,self.secretKey = secretId,secretKey
self.mailman = mailman()
self.receivers = ['tiexin.yang@yoho.cn','chunhua.zhang@yoho.cn']
self.client = QcloudApi(self.secretId,self.secretKey)
def LocateInstanceByIp(self,privateIp):
params = {
"Action": "DescribeInstances",
"Filters.0.Name": "private-ip-address",
"Filters.0.Values.0": privateIp
}
result = self.client.do_query(params,"cvm.ap-beijing.tencentcloudapi.com/",api_version=3)
instances = result["Response"]["InstanceSet"]
if len(instances) == 0:
print "查询结果为空,请确认输入IP无误后再试"
return False
else:
instance = instances[0]
instanceId,instanceName = instance["InstanceId"],instance["InstanceName"]
return instanceId,instanceName
def ReturnInstanceById(self,instanceId):
params = {
"Action":"TerminateInstances",
"InstanceIds.0":instanceId
}
result = self.client.do_query(params,"cvm.ap-beijing.tencentcloudapi.com")
return result
def ReturnInstanceByIp(self,privateIp):
print '查询IP对应的实例ID'
result = self.LocateInstanceByIp(privateIp)
if result:
instanceId,instanceName = result
print u'即将退还实例...请确认如下信息无误:\n\t实例ID:{0}\n\t实例IP:{1}\n\t实例名称:{2}'.format(instanceId,privateIp,instanceName)
feedBack = str(raw_input('确认?(Y/N): ')).upper()
if feedBack == 'Y':
print '开始退还实例...{0}'.format(instanceId)
self.ReturnInstanceById(instanceId)
print '实例退还成功!'
print '开始注销zabbix host...'
delete_host_by_ip(privateIp)
return 0
else:
print '任务取消'
return 0
else:
return 0
if __name__ == '__main__':
demo = consoleRobot()
demo.ReturnInstanceByIp(sys.argv[1])
... ...
... ... @@ -16,13 +16,13 @@ password = "rknTpkVa@6ItBP"
zapi = ZabbixAPI(server=server, path="", log_level=0)
zapi.login(username, password)
def get_args():
def get_args(private_ip=''):
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--hosts", help="host ips")
# 解析所传入的参数
args = parser.parse_args()
if not args.hosts:
args.hosts = raw_input('hosts(ip): ')
args.hosts = raw_input('hosts(ip): ') if not private_ip else private_ip
return args
def get_host_id(hosts):
... ... @@ -36,16 +36,20 @@ def get_host_id(hosts):
)
host_id = []
host_id.append([host["hostid"] for host in get_host_id])
return host_id[0]
if host_id:
return host_id[0]
else:
return False
def delete_host(hosts_id):
def delete_host_by_id(hosts_id):
if hosts_id:
hosts_delete = zapi.host.delete(hosts_id)
return "host delete success!"
return "Zabbix host {0} 已成功删除!".format(hosts_id)
else:
return "host not found!"
return "Host 不存在"
if __name__ == "__main__":
args = get_args()
def delete_host_by_ip(private_ip):
args = get_args(private_ip=private_ip)
hosts_id = get_host_id(args.hosts)
print delete_host(hosts_id)
print delete_host_by_id(hosts_id)
... ...