自动查看eip绑定的ecs
【摘要】 import timeimport jsonimport paramikofrom huaweicloudsdkcore.auth.credentials import BasicCredentialsfrom huaweicloudsdkcore.exceptions import exceptionsfrom huaweicloudsdkvpc.v2.region.vpc_region ...
import time
import json
import paramiko
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion
from huaweicloudsdkvpc.v2 import *
from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
from huaweicloudsdkecs.v2 import *
def ecs(client):
try:
request = ListServersDetailsRequest()
response = client.list_servers_details(request)
return response
except exceptions.ClientRequestException as e:
print(e.status_code)
print(e.request_id)
print(e.error_code)
print(e.error_msg)
def vpc(client, routetable_id, routes):
try:
request = UpdateRouteTableRequest()
request.routetable_id = routetable_id
listUpdateRouteTableReqRoutesRoutes = routes
listUpdateRouteTableReqRoutesRoutetable = {
"mod": listUpdateRouteTableReqRoutesRoutes
}
routetableUpdateRouteTableReq = UpdateRouteTableReq(
name="zhenxing-01-rtb-1",
routes=listUpdateRouteTableReqRoutesRoutetable
)
request.body = UpdateRoutetableReqBody(
routetable=routetableUpdateRouteTableReq
)
response = client.update_route_table(request)
print(response)
except exceptions.ClientRequestException as e:
print(e.status_code)
print(e.request_id)
print(e.error_code)
print(e.error_msg)
def loopMonitor():
while True:
zhenxing(vpc_id)
time.sleep(5)
def zhenxing(vpc_id):
# 返回json格式的ecs列表
ecs_list = json.loads(str(ecs(ecs_client)))
# 返回绑定eip的ecs的名字
ecs_eip = '没有ECS绑定EIP'
for i in range(len(ecs_list['servers'])):
for e in range(len(ecs_list['servers'][i]['addresses'][vpc_id])):
if ecs_list['servers'][i]['addresses'][vpc_id][e]['OS-EXT-IPS:type'] == 'floating':
ecs_eip = ecs_list['servers'][i]['name']
# 获取eip默认绑定ecs
global ecs_default
# 判断eip有没有换绑
# 无改变
if ecs_eip == ecs_default:
print("eip绑定无改变")
# 换绑到ecs1
elif ecs_eip == 'ecs-1':
print('换绑到ecs1')
ecs_default = ecs_eip
ecsname = ecs_eip
ecsname2 = 'ecs-2'
ssh_ecs(vpc_id, ecsname, ecsname2)
# 换绑到ecs2
elif ecs_eip == 'ecs-2':
print('换绑到ecs2')
ecs_default = ecs_eip
ecsname = ecs_eip
ecsname2 = 'ecs-1'
ssh_ecs(vpc_id, ecsname, ecsname2)
# 没有ecs绑定eip
else:
print('没有ECS绑定EIP')
if __name__ == "__main__":
ak = "5UD814LDI"
sk = "DgSPFyMEVRl1"
credentials = BasicCredentials(ak, sk)
ecs_client = EcsClient.new_builder() \
.with_credentials(credentials) \
.with_region(EcsRegion.value_of("cn-north-4")) \
.build()
vpc_client = VpcClient.new_builder() \
.with_credentials(credentials) \
.with_region(VpcRegion.value_of("cn-north-4")) \
.build()
# 默认绑定eip的ecs
ecs_default = "ecs-1"
# vpc的id
vpc_id = 'b81a6a87'
# 运行循环
loopMonitor()
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)