zoukankan      html  css  js  c++  java
  • py脚本---------自动切换ECS的EIP

    切换ecs的eip的脚本
    调用顺序:

    1. 8 按顺序执行函数

    2. 1 getEcsEip函数获取ecs信息-->

    3. 6 unassociate_eip_address函数解绑并调用

    4. 3 函数ReleaseEipAddress释放eip -->

    5. 4 apply_eip函数创建新的EIP -->

    6. 5 associate_eip_address函数申请将新EIP绑定到对应区域ecs -->

    7. 7 get_eip_info函数从request中获取eip地址并放入response -->

    8. 2 dingdingtalksend函数发送消息给钉钉

    cat eip_quick_optv3.py
    
    # encoding=utf-8
    import sys
    import json
    from aliyunsdkcore.client import AcsClient
    from aliyunsdkcore.acs_exception.exceptions import ClientException
    from aliyunsdkcore.acs_exception.exceptions import ServerException
    from aliyunsdkvpc.request.v20160428.AllocateEipAddressRequest import AllocateEipAddressRequest
    from aliyunsdkvpc.request.v20160428.AssociateEipAddressRequest import AssociateEipAddressRequest
    from aliyunsdkvpc.request.v20160428.UnassociateEipAddressRequest import UnassociateEipAddressRequest
    from aliyunsdkvpc.request.v20160428.DescribeEipAddressesRequest import DescribeEipAddressesRequest
    from aliyunsdkvpc.request.v20160428.ReleaseEipAddressRequest import ReleaseEipAddressRequest
    from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
    import time
    import redis
    import requests
    import os
    import psutil
    
    #阿里云access key信息及区域
    client = AcsClient('xx', 'yy', 'cn-shenzhen')
    
    #需要切换的ecs实例ID
    ecsinstanceids = ['i-wz1', 'i-wz2', 'i-wz3', 'i-wz4', 'i-wz5','i-wz6']
    
    #新eip的列表
    neweiplist = []
    
    
    #1查看ecs具体Instance信息,包含eip信息
    def getEcsEip(ecsinstanceids):
        #调用查询ecs信息的SDK
        request = DescribeInstancesRequest()
        request.set_accept_format('json')
        request.set_PageSize(100)
        request.set_InstanceIds(ecsinstanceids)
        response = client.do_action_with_exception(request)
        return json.loads(response)['Instances']['Instance']
    
    #2.发送消息到钉钉群
    def dingdingtalksend(bjname,sj):
        dingdingurl = 'https://oapi.dingtalk.com/robot/send?
    
    access_token=8a3fafa133d1a5820efdb05aa40dbfa357fe3767386cffa1d6887492c0309422'
        data = json.dumps({'msgtype': 'markdown','markdown': {'title':'代理切换中','text': '生产环境EIP切换消息:  
    
    
    '+bjname+'
    '+sj} })
        r = requests.post(dingdingurl, data, headers={'Content-Type': 'application/json;charset=utf-8'})
        print(r.text)
    
    
    #3.释放指定的弹性公网IP,传参:json格式,指定eip的id(eipid)
    def ReleaseEipAddress(eipid, encoding='utf-8'):
        #ReleaseEipAddressRequest
        request = ReleaseEipAddressRequest()
        request.set_accept_format('json')
        request.set_AllocationId(eipid)
        client.do_action_with_exception(request)
    
    #4.创建新的EIP,传参:json格式,带宽峰值5M,线路类型BGP,后付费模式,按使用流量付费,
    def apply_eip(encoding='utf-8'):
        request = AllocateEipAddressRequest()
        request.set_accept_format('json')
        request.set_Bandwidth("5")
        request.set_ISP("BGP")
        request.set_InstanceChargeType("PostPaid")
        request.set_InternetChargeType("PayByTraffic")
        response = client.do_action_with_exception(request)
        return dict(json.loads(str(response, encoding='utf-8')))['AllocationId']
    
    #5.申请将新EIP绑定到对应区域ecs,传参:json格式,指定eip的id(eipid),指定ecs的实例id(ecs_id),实例类型为ecs
    def associate_eip_address(eip_id, ecs_id, encoding='utf-8'):
        request = AssociateEipAddressRequest()
        request.set_accept_format('json')
        request.set_InstanceId(eip_id)
        request.set_AllocationId(ecs_id)
        request.set_InstanceType("EcsInstance")
        client.do_action_with_exception(request)
        print("申请绑定新EIP:", ecs_id)
    
    #6.解绑并释放ecs_id中的eip_id,传参:
    def unassociate_eip_address(eip_id, ecs_id, encoding='utf-8'):
        #调用释放eip接口UnassociateEipAddressRequest
        request = UnassociateEipAddressRequest()
        request.set_accept_format('json')
        request.set_AllocationId(ecs_id)
        request.set_InstanceId(eip_id)
        request.set_InstanceType("EcsInstance")
        response = client.do_action_with_exception(request)
        print("解绑并释放EIP:", ecs_id)
        time.sleep(4)
        #释放指定的eip
        ReleaseEipAddress(ecs_id, encoding='utf-8')
    
    #7.从request中获取eip地址并放入response
    def get_eip_info(encoding='utf-8'):
        request = DescribeEipAddressesRequest()
        request.set_accept_format('json')
        request.set_PageSize(100)
        response = client.do_action_with_exception(request)
        return json.loads(str(response, encoding='utf-8'))
    
    #8.实例化后执行的内容
    def main():
        #调用getEcsEip函数
        for ecsinfo in getEcsEip(ecsinstanceids):
    	#获取ecs对应eip实例ID放入到response
            AllocationId = ecsinfo['EipAddress']['AllocationId']
    	#获取ecs的实例ID
            InstanceId = ecsinfo['InstanceId']
            print(AllocationId)
            print(InstanceId)
    	#如果eip实例ID值存在,就调用unassociate_eip_address函数解绑并释放eip,调用apply_eip函数创建eip
    	#InstanceId是eip_id,AllocationId是ecs_id
            if AllocationId:
                unassociate_eip_address(InstanceId, AllocationId, encoding='utf-8')
                newAllocationId = apply_eip()
            #如果eip实例ID值不存在,也调用apply_eip函数创建eip
            else:
                newAllocationId = apply_eip()
            #调用associate_eip_address函数将新eip绑定到ecs实例ID中
            associate_eip_address(InstanceId, newAllocationId, encoding='utf-8')
        #调用get_eip_info函数从request中获取eip地址并放入response
        eipinfo = get_eip_info()
        #循环判断ecs实例ID并命一个别名,后面发给钉钉
        for eipline in eipinfo['EipAddresses']['EipAddress']:
            obj = {}
            if eipline['InstanceId'] in ecsinstanceids:
                if eipline['InstanceId'] == 'i-wz9ipft9swsqvwi40637':
                    Name = 'proxy1'
                elif eipline['InstanceId'] == 'i-wz9ipft9swsqvwi40639':
                    Name = 'proxy2'
                elif eipline['InstanceId'] == 'i-wz9ipft9swsqvwi4063b':
                    Name = 'proxy3'
                elif eipline['InstanceId'] == 'i-wz9ipft9swsqvwi40638':
                    Name = 'proxy4'
                elif eipline['InstanceId'] == 'i-wz9ipft9swsqvwi4063a':
                    Name = 'proxy5'
                elif eipline['InstanceId'] == 'i-wz96rc22e3e8cesooegc':
                    Name = 'proxy6'
                elif eipline['InstanceId'] == 'i-wz96rc22e3e8cesooegd':
                    Name = 'proxy7'
                elif eipline['InstanceId'] == 'i-wz9dsw8flxbfj81f4i6p':
                    Name = 'proxy8'
                elif eipline['InstanceId'] == 'i-wz9dsw8flxbfj81f4i6q':
                    Name = 'proxy9'
                else:
                    Name = 'proxy'
    	    #将别名替换eipinfo的IP地址
                obj[Name] = eipline['IpAddress']
                #将obj放入到neweiplist字典内
                neweiplist.append(obj)
        #调用dingdingtalksend函数将neweiplist字典转换成字符串发给钉钉群
        dingdingtalksend("自动切换完成最新EIP信息如下:
    ", str(neweiplist))
    
    #实例化并调用main函数
    if __name__ == '__main__':
        sys.exit(main())
    
  • 相关阅读:
    Android 反编译 -smali语法
    软件工程 -- 开发模型
    Android application testing with the Android test framework
    Android Framework 简介
    Android 系统信息的获取
    在 Ubuntu 上搭建 Hadoop 分布式集群 Eclipse 开发环境
    ARM汇编指令
    Java 面试/笔试题神整理 [Java web and android]
    vim/vi用法总结
    修改MIGO或者ML81N产生的会计凭证项目文本增强
  • 原文地址:https://www.cnblogs.com/wangchengshi/p/15248114.html
Copyright © 2011-2022 走看看