阿里云自动更换EIP脚本

阿里云自动更换EIP脚本

需要安装阿里云SDK: pip install aliyun-python-sdk-ecs 使用方式:python change_eip.py

centos7先安装pip和模块:

1
2
3
4
5
6
wget https://bootstrap.pypa.io/pip/2.7/get-pip.py
python get-pip.py
pip install aliyun-python-sdk-ecs
pip install aliyun-python-sdk-core
pip install requests
pip install --ignore-installed requests

config.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#coding:utf-8

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#账号的key和secret
access_id='xxxxxx'
access_key_secret='xxxxxxxxx'
#ECS_ID 服务器ID
ecs_vpc_id=''
#带宽大小,200 就是 200M带宽
eip_bandwidth=200
#区域:cn-hongkong(香港),ap-southeast-1(新加坡)
ecs_regionid=''
#流量计费方式:PayByTraffic(按流量收费),PayByBandwidth(按带宽收费)
ecs_chargetype='PayByTraffic'

eip.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python
#coding:utf-8

import json
import sys
from config import access_id,access_key_secret,ecs_regionid,ecs_chargetype
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526 import AllocateEipAddressRequest,ReleaseEipAddressRequest,AssociateEipAddressRequest,UnassociateEipAddressRequest,DescribeEipAddressesRequest

clt = client.AcsClient(access_id,access_key_secret,ecs_regionid)

def create_eip_address(regionid=ecs_regionid,chargetype=ecs_chargetype,bandwidth=200,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

def delete_unassociate_eip_address():
request=DescribeEipAddressesRequest.DescribeEipAddressesRequest()
request.set_accept_format('json')
request.set_Status('Available')
request.set_PageSize(50)
try:
result =json.loads(clt.do_action(request))
except:
print("Get Eip address list error.")
sys.exit()
eip_list=[]
if result:
eip_list=result['EipAddresses']['EipAddress']

for eip in eip_list:
#print eip['IpAddress'],eip['AllocationId']
result=delete_eip_address(eip['AllocationId'])
if result:
print("EIP %s is deleted.") % eip['IpAddress']


if __name__ == "__main__":
delete_unassociate_eip_address()

instance.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#coding:utf-8

import json
import sys
from config import access_id,access_key_secret,ecs_vpc_id,ecs_regionid
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest

clt = client.AcsClient(access_id,access_key_secret,ecs_regionid)

def instance_info(instanceid,fmt='json'):
request=DescribeInstancesRequest.DescribeInstancesRequest()
request.set_accept_format(fmt)
request.set_InstanceIds([instanceid])

try:
result=clt.do_action(request)
r_dict=json.loads(result)
except:
print("Get Instance Info Failed.")
sys.exit()

if r_dict.has_key('TotalCount') and r_dict['TotalCount'] != 0:
instance=r_dict['Instances']['Instance'][0]
return instance
else:
print("Instance id %s is not exist.") % instanceid
sys.exit()

if __name__ == "__main__":
print instance_info(ecs_vpc_id)['EipAddress']

change_eip.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python
#coding:utf-8

import sys
import time
from config import ecs_vpc_id,eip_bandwidth
from eip import create_eip_address,delete_eip_address,associate_eip_address,unassociate_eip_address
from instance import instance_info

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()

#暂停10秒等待新的EIP申请成功后,在绑定
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


if __name__ == "__main__":
print main()

阿里云自动更换EIP脚本
https://johnnysxy.github.io/2023/04/26/阿里云自动更换EIP脚本/
作者
Johnny Song
发布于
2023年4月26日
许可协议