Python實現阿里雲ecs主機公網IP的切換功能程式

來源:互聯網
上載者:User

對於採集、註冊或者代理來說,如果伺服器公網IP可以自動切換,那麼可能會少很多麻煩。最近博主就使用阿里雲的api實現了這個小功能。實現的步驟比較簡單,首先需要申請阿里雲的api key。然後申請vpc專用網路,普通經典ecs主機無法掛載彈性IP,在剛剛申請的專用網路中開通一台ecs伺服器。接著申請Elastic IP Address。最後把這個公網IP掛載到專用網路下的ecs。完成後付費包括兩部分,一個是ecs費用(包年或包月,預付費),另外是彈性公網eip的費用(按量、後付費)。

接下來開始用python來實現下。阿里雲提供了python的sdk,這裡博主就直接用sdk了。

第一步:建立vpc和ecs

這個直接在阿里雲頁面上建立就可以。

第二步:安裝sdk

pip install aliyun-python-sdk-ecs
不清楚的可以參考阿里雲:https://develop.aliyun.com/sdk/python

第三步:Elastic IP Address方法

代碼類似如下:

申請

def create_eip_address(regionid='cn-hongkong',chargetype='PayByBandwidth',bandwidth=1,fmt='json'):
    request=AllocateEipAddressRequest.AllocateEipAddressRequest()
    request.set_accept_format(fmt)
    request.set_Bandwidth(bandwidth)
    request.add_query_param('RegionId',regionid)
    request.add_query_param('InternetChargeType',chargetype)
   
    try:
        result=clt.do_action(request)
        r_dict=json.loads(result)
    except:
        print("Create EIP Address Failed.")
        sys.exit()
   
    if r_dict.has_key('EipAddress'):
        res={}
        res['ip']=r_dict['EipAddress']
        res['id']=r_dict['AllocationId']
        return res
    else:
        print(r_dict['Message'])
        sys.exit()
刪除

def delete_eip_address(eipid,fmt='json'):
    request=ReleaseEipAddressRequest.ReleaseEipAddressRequest()
    request.set_accept_format(fmt)
    request.set_AllocationId(eipid)
    try:
        result=clt.do_action(request)
        r_dict=json.loads(result)
    except:
        print("Delete EIP Address Failed.")
        sys.exit()
   
    if r_dict.has_key('Code'):
        print(r_dict['Message'])
        sys.exit()
    else:
        return r_dict
綁定

def associate_eip_address(allocationid,instanceid,instancetype='EcsInstance',fmt='json'):
    request=AssociateEipAddressRequest.AssociateEipAddressRequest()
    request.set_accept_format(fmt)
    request.set_AllocationId(allocationid)
    request.add_query_param('InstanceType',instancetype)
    request.set_InstanceId(instanceid)
    try:
        result=clt.do_action(request)
        r_dict=json.loads(result)
    except:
        print("Associate EIP Address Failed.")
        sys.exit()
       
    if r_dict.has_key('Code'):
        print(r_dict['Message'])
        sys.exit()
    else:
        return r_dict
解除綁定

def unassociate_eip_address(allocationid,instanceid,instancetype='EcsInstance',fmt='json'):
    request=UnassociateEipAddressRequest.UnassociateEipAddressRequest()
    request.set_accept_format(fmt)
    request.set_AllocationId(allocationid)
    request.add_query_param('InstanceType',instancetype)
    request.set_InstanceId(instanceid)
    try:
        result=clt.do_action(request)
        r_dict=json.loads(result)
    except:
        print("Unassociate EIP Address Failed.")
        sys.exit()
       
    if r_dict.has_key('Code'):
        print(r_dict['Message'])
        sys.exit()
    else:
        return r_dict
以上就是一些Elastic IP Address的4個方法,分別實現IP的申請、刪除、綁定和解除綁定的功能。

第四步:更換IP

更換IP步驟:

擷取ECS資訊 --有EIP--> 解除綁定EIP -> 刪除老EIP -->申請新EIP --> 綁定新EIP到ECS
    |                                              ^
    |                                              |
    -------------------無EIP------------------------
在刪除老的公網IP前需要判斷是否真的解除綁定,不然解除綁定請求提交給阿里雲後馬上刪除老的EIP可能會因為eip還未解除綁定而報錯。

代碼類似如下:

def main():
    #擷取當前vpc下ecs主機的eip
    instance=instance_info(ecs_vpc_id)
    eip_id=instance['EipAddress']['AllocationId']
    eip_ip=instance['EipAddress']['IpAddress']
    if not instance:
        print("Get instance info error.")
        sys.exit()
    else:
        if not eip_id:
            print("Instance %s has not associate eip address.") % ecs_vpc_id
        else:
            print("Instance: %s ,Eip id: %s .") % (ecs_vpc_id,eip_id)
   
            #解除綁定eip
            result_unassociate=unassociate_eip_address(eip_id, ecs_vpc_id)
            if not result_unassociate:
                print("Unassociate eip address from %s error.") % ecs_vpc_id
                sys.exit()
           
            #判斷真正解除綁定後開始刪除老的eip
            while True:
                eip_id_tmp=instance_info(ecs_vpc_id)['EipAddress']['AllocationId']
                if not eip_id_tmp:
                    #刪除老的eip
                    result_release=delete_eip_address(eip_id)
                    if not result_release:
                        print("Release eip %s error.") % eip_id
                        sys.exit()
                    break
                else:
                    continue
                time.sleep(1)
   
    #申請新eip
    result_allocate=create_eip_address(bandwidth=eip_bandwidth)
    if not result_allocate:
        print("Allocate new eip address error.")
        sys.exit()
   
    #time.sleep(10)
   
    #綁定eip
    result_associate=associate_eip_address(result_allocate['id'], instanceid=ecs_vpc_id)
    if not result_associate:
        print("Associate eip %s to instance %s error.") % (result_allocate,ecs_vpc_id)
        sys.exit()
    else:
        print("Associate eip %s to instance %s successfully.") % (result_allocate['ip'],ecs_vpc_id)
        ip_dict={
            'oip':eip_ip,
            'nip':result_allocate['ip']
        }
        return ip_dict
 

以上代碼我放在github上,地址:https://github.com/zhangnq/scripts/tree/master/python/aliyun,感興趣的朋友也可以看下

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.