ecs被python连接
【摘要】 def loopMonitor(): while True: zhenxing(vpc_id) time.sleep(5)def ssh_ecs(vpc_id, ecsname, ecsname2): # 路由表id routetable_id = '3a-4a1' # 返回ecs name和私网ip ecs_list = json....
def loopMonitor():
while True:
zhenxing(vpc_id)
time.sleep(5)
def ssh_ecs(vpc_id, ecsname, ecsname2):
# 路由表id
routetable_id = '3a-4a1'
# 返回ecs name和私网ip
ecs_list = json.loads(str(ecs(ecs_client)))
ecs_ip = {}
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'] == 'fixed':
ecs_ip[ecs_list['servers'][i]['name']] = ecs_list['servers'][i]['addresses'][vpc_id][e]['addr']
# 返回ecs name 和 id
ecs_id = {}
for i in range(len(ecs_list['servers'])):
ecs_id[ecs_list['servers'][i]['name']] = ecs_list['servers'][i]['id']
# 设置vpc新的路由规则
routes = [{}]
routes[0]['type'] = 'ecs'
routes[0]['destination'] = '0.0.0.0/0'
routes[0]['nexthop'] = ecs_id[ecsname]
vpc(vpc_client, routetable_id, routes)
print('vpc路由表规则到ecs1')
# 在新主机上添加 IPtables
# trans = paramiko.Transport((ecs_ip[ecsname], 22))
# trans.connect(username='root', password='ecs-01-pass')
# ssh = paramiko.SSHClient()
# ssh._transport = trans
# ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh.exec_command(
# 'echo net.ipv4.ip_forward = 1 >> /etc/sysctl.conf && sysctl -p && iptables -t nat -A POSTROUTING -s '
# '192.168.1.0/24 -j SNAT --to ' +
# ecs_ip[ecsname])
# trans.close()
print('创建新iptables')
# 在原主机 上删除iptables
# trans = paramiko.Transport((ecs_ip[ecsname2], 22))
# trans.connect(username='root', password='ecs-01-pass')
# ssh = paramiko.SSHClient()
# ssh._transport = trans
# ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh.exec_command("iptables -t nat -F POSTROUTING && sed -i '$d' /etc/sysctl.conf && sysctl -p ")
# trans.close()
print('删除旧iptables')
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')
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)