使用python sdk添加删除阿里云pvc路由

news2024/9/20 1:07:58

1. 前言

由于线路供应商sdwan存在单点问题,需要实现线路高可用解决方案,需要设计自动切换阿里云vpc路由解决方案。通过阿里云文档了解,可通过阿里云专有网络Python SDK,通过sdk实现创建、删除、查询等vpc网络相关操作(创建/删除路由表、创建/删除自定义路由等)。

环境准备

  • Python 2.7及3.x环境(这里使用python3.9.6)
  • 配置阿里云账号和访问密钥(AccessKey),权限:AliyunVPCFullAccess
  • 安装Alibaba Cloud SDK for Python

2. 安装

安装Alibaba Cloud SDK

# 安装模块
pip install alibabacloud_tea_openapi
pip install alibabacloud_vpc20160428==2.0.0
pip install aliyun-python-sdk-vpc==3.0.25

# 安装sdk示例库,完成环境初始化
git clone https://github.com/aliyun/aliyun-openapi-python-sdk-examples.git
cd aliyun-openapi-python-sdk-examples/sdk_examples/
python setup.py install

安装效果如下

3. 使用方法 

在解压的目录.sdk_examples/examples/,可以看到除了vpc的py脚本,还有slb,eip等,根据需要可自行查看修改,这里使用sdk_examples/examples/vpc/vpc_route_entry.py进行修改,原代码为

#encoding=utf-8
import sys
import json
import time

from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
from aliyunsdkvpc.request.v20160428 import CreateRouteEntryRequest
from aliyunsdkvpc.request.v20160428 import DeleteRouteEntryRequest
from aliyunsdkvpc.request.v20160428 import DescribeRouteTablesRequest
from sdk_lib.exception import ExceptionHandler
from sdk_lib.check_status import CheckStatus
from sdk_lib.common_util import CommonUtil
from sdk_lib.sdk_vswitch import VSwitch
from sdk_lib.sdk_route_table import RouteTable
from sdk_lib.consts import *

class RouteEntry(object):
    def __init__(self, client):
        self.client = client

    def create_route_entry(self, params):
        """
        create_route_entry: 创建route_entry路由条目
        官网API参考链接: https://help.aliyun.com/document_detail/36012.html
        """
        try:
            request = CreateRouteEntryRequest.CreateRouteEntryRequest()
            # 路由表ID
            request.set_RouteTableId(params['route_table_id'])
            # 自定义路由条目的目标网段
            request.set_DestinationCidrBlock(params['destination_cidr_block'])
            # 下一跳的类型
            request.set_NextHopType(params['nexthop_type'])
            # 下一跳实例的ID
            request.set_NextHopId(params['nexthop_id'])
            response = self.client.do_action_with_exception(request)
            response_json = json.loads(response)
            # 判断router entry状态是否可用
            if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                        self.describe_route_entry_status,
                                        AVAILABLE, params['route_table_id']):
                return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)

    def delete_route_entry(self, params):
        """
        delete_route_entry: 删除route_entry路由条目
        官网API参考链接: https://help.aliyun.com/document_detail/36013.html
        """
        try:
            request = DeleteRouteEntryRequest.DeleteRouteEntryRequest()
            # 路由条目所在的路由表的ID
            request.set_RouteTableId(params['route_table_id'])
            # 路由条目的目标网段
            request.set_DestinationCidrBlock(params['destination_cidr_block'])
            # 下一跳实例的ID
            request.set_NextHopId(params['nexthop_id'])
            response = self.client.do_action_with_exception(request)
            response_json = json.loads(response)
            time.sleep(DEFAULT_TIME)
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)

    def describe_route_entry_vrouter(self, params):
        """
        describe_route_entry_vrouter: 查询route_entry路由条目
        官网API参考链接: https://help.aliyun.com/document_detail/36014.html
        """
        try:
            request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
            # 路由表所属的VPC路由器或边界路由器的ID
            request.set_VRouterId(params['vrouter_id'])
            # 路由表的ID
            request.set_RouteTableId(params['route_table_id'])
            response = self.client.do_action_with_exception(request)
            response_json = json.loads(response)
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)

    def describe_route_entry(self, route_table_id):
        """
        describe_route_entry: 查询route_entry路由条目
        官网API参考链接: https://help.aliyun.com/document_detail/36014.html
        """
        try:
            request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
            request.set_RouteTableId(route_table_id)
            response = self.client.do_action_with_exception(request)
            response_json = json.loads(response)
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)

    def describe_route_entry_status(self, route_table_id):
        """
        describe_route_entry_status: 查询route_entry路由条目当前状态
        """
        response = self.describe_route_entry(route_table_id)
        return response["RouteTables"]["RouteTable"][0]["RouteEntrys"]["RouteEntry"][0]["Status"]

def main():
    client = ACS_CLIENT
    vswitch = VSwitch(client)
    route_table = RouteTable(client)
    route_entry = RouteEntry(client)

    params = {}
    params['route_table_name'] = "sdk_route_table"
    params['destination_cidr_block'] = "0.0.0.0/0"
    params['nexthop_id'] = "i-xxx"
    params['nexthop_type'] = "Instance"

    params['vpc_id'] = "vpc-xxx"
    params['vswitch_id'] = "vsw-xxx"

    #创建route table
    route_table_json = route_table.create_route_table(params)
    CommonUtil.log("create_route_table", route_table_json)

    #查询vswitch
    vswitch_json = vswitch.describe_vswitch_attribute(params)
    CommonUtil.log("describe_vswitch_attribute", vswitch_json)

    #route table绑定vswitch
    params['route_table_id'] = route_table_json['RouteTableId']
    associate_json = route_table.associate_route_table(params)
    CommonUtil.log("associate_route_table", associate_json)

    #创建路由条目
    create_route_entry_json = route_entry.create_route_entry(params)
    CommonUtil.log("create_route_entry", create_route_entry_json)
    
    #删除路由条目
    delete_route_entry_json = route_entry.delete_route_entry(params)
    CommonUtil.log("delete_route_entry", delete_route_entry_json)

    #route table解绑vswitch
    unassociate_json = route_table.unassociate_route_table(params)
    CommonUtil.log("unassociate_route_table", unassociate_json)

    #删除route table
    delete_route_table_json = route_table.delete_route_table(params)
    CommonUtil.log("delete_route_table", delete_route_table_json)


if __name__ == "__main__":
    sys.exit(main())

改为两个py脚本,一个添加路由,一个删除路由

添加路由脚本:add_route.py

#encoding=utf-8
import sys
import json
import time

from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
from aliyunsdkvpc.request.v20160428 import CreateRouteEntryRequest
from aliyunsdkvpc.request.v20160428 import DeleteRouteEntryRequest
from aliyunsdkvpc.request.v20160428 import DescribeRouteTablesRequest
from sdk_lib.exception import ExceptionHandler
from sdk_lib.check_status import CheckStatus
from sdk_lib.common_util import CommonUtil
from sdk_lib.sdk_vswitch import VSwitch
from sdk_lib.sdk_route_table import RouteTable
from sdk_lib.consts import *

class RouteEntry(object):
    def __init__(self, client):
        self.client = client
    
    def create_route_entry(self, params):
        """
        create_route_entry: 创建route_entry路由条目

        """
        try:
            request = CreateRouteEntryRequest.CreateRouteEntryRequest()
            # 路由表ID
            request.set_RouteTableId(params['route_table_id'])
            # 自定义路由条目的目标网段
            request.set_DestinationCidrBlock(params['destination_cidr_block'])
            # 下一跳的类型
            request.set_NextHopType(params['nexthop_type'])
            # 下一跳实例的ID
            request.set_NextHopId(params['nexthop_id'])
            response = self.client.do_action_with_exception(request)
            response_json = json.loads(response)
            # 判断router entry状态是否可用
            if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                        self.describe_route_entry_status,
                                        AVAILABLE, params['route_table_id']):
                return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)

    def describe_route_entry_status(self, route_table_id):
        """
        describe_route_entry_status: 查询route_entry路由条目当前状态

        """
        response = self.describe_route_entry(route_table_id)
        return response["RouteTables"]["RouteTable"][0]["RouteEntrys"]["RouteEntry"][0]["Status"]

    def describe_route_entry_vrouter(self, params):
        """
        describe_route_entry_vrouter: 查询route_entry路由条目

        """
        try:
            request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
            # 路由表所属的VPC路由器或边界路由器的ID
            request.set_VRouterId(params['vrouter_id'])
            # 路由表的ID
            request.set_RouteTableId(params['route_table_id'])
            response = self.client.do_action_with_exception(request)
            response_json = json.loads(response)
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)

    def describe_route_entry(self, route_table_id):
        """
        describe_route_entry: 查询route_entry路由条目

        """
        try:
            request = DescribeRouteTablesRequest.DescribeRouteTablesRequest()
            request.set_RouteTableId(route_table_id)
            response = self.client.do_action_with_exception(request)
            response_json = json.loads(response)
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)

def main():
    # 这里填上上面创建的阿里云帐号accesskey和secretkey,以及vpc地域
    client = AcsClient(
            '***',
            '***',
            'cn-guangzhou')
    vswitch = VSwitch(client)
    route_table = RouteTable(client)
    route_entry = RouteEntry(client)
    # 变量params参数,根据需要添加路由,pvc id,switch id和路由表名称
    params = {}
    params['route_table_name'] = "sdk_route_table"
    params['destination_cidr_block'] = "0.0.0.0/0"
    params['nexthop_id'] = "i-xxx"
    params['nexthop_type'] = "Instance"

    params['vpc_id'] = "vpc-xxx"
    params['vswitch_id'] = "vsw-xxx"


    #创建路由条目
    create_route_entry_json = route_entry.create_route_entry(params)
    CommonUtil.log("create_route_entry", create_route_entry_json)

if __name__ == "__main__":
    sys.exit(main())

使用方法:

python add_route.py

删除路由脚本:del_route.py

#encoding=utf-8
import sys
import json
import time

from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
from aliyunsdkvpc.request.v20160428 import CreateRouteEntryRequest
from aliyunsdkvpc.request.v20160428 import DeleteRouteEntryRequest
from aliyunsdkvpc.request.v20160428 import DescribeRouteTablesRequest
from sdk_lib.exception import ExceptionHandler
from sdk_lib.check_status import CheckStatus
from sdk_lib.common_util import CommonUtil
from sdk_lib.sdk_vswitch import VSwitch
from sdk_lib.sdk_route_table import RouteTable
from sdk_lib.consts import *

class RouteEntry(object):
    def __init__(self, client):
        self.client = client
    
    def delete_route_entry(self, params):
        """
        delete_route_entry: 删除route_entry路由条目

        """
        try:
            request = DeleteRouteEntryRequest.DeleteRouteEntryRequest()
            # 路由条目所在的路由表的ID
            request.set_RouteTableId(params['route_table_id'])
            # 路由条目的目标网段
            request.set_DestinationCidrBlock(params['destination_cidr_block'])
            # 下一跳实例的ID
            request.set_NextHopId(params['nexthop_id'])
            response = self.client.do_action_with_exception(request)
            response_json = json.loads(response)
            time.sleep(DEFAULT_TIME)
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)

 

def main():
    # 这里填上上面创建的阿里云帐号accesskey和secretkey,以及vpc地域
    client = AcsClient(
            '***',
            '***',
            'cn-guangzhou')
    vswitch = VSwitch(client)
    route_table = RouteTable(client)
    route_entry = RouteEntry(client)
    # 变量params参数,根据需要添加路由,pvc id,switch id和路由表名称
    params = {}
    params['route_table_name'] = "sdk_route_table"
    params['destination_cidr_block'] = "0.0.0.0/0"
    params['nexthop_id'] = "i-xxx"
    params['nexthop_type'] = "Instance"

    params['vpc_id'] = "vpc-xxx"
    params['vswitch_id'] = "vsw-xxx"


    #删除路由条目
    delete_route_entry_json = route_entry.delete_route_entry(params)
    CommonUtil.log("delete_route_entry", delete_route_entry_json)

if __name__ == "__main__":
    sys.exit(main())

使用方法:

python del_route.py

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/705223.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何与德科斯米尔Draexlmaier 建立 EDI 连接?

德科斯米尔Draexlmaier(以下简称为DRX)是一家总部位于德国的汽车零部件供应商和系统集成商,如今已成为全球领先的汽车内部装饰系统、电气和电子系统、电缆技术以及储能系统的制造商之一。EDI 帮助DRX与其交易伙伴之间实现信息流的一致性、无误…

CHATGPT使用笔记

CHATGPT是帮你做事,而不是替你做事 1、联网插件: 使用Webpilot插件联网时还可以同时使用其它两种插件(一次可以同时使用三个插件),而使用Web Browsing插件功能联网时无法使用插件功能(联网功能和插件只能…

SpringBoot2+Vue2实战(八)文件上传实现

一、文件上传 创建数据库表 Files import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data;Data TableName("sys_file") public cl…

18.RocketMQ中消息重复的场景和幂等处理

highlight: arduino-light 消息重复的场景 发送消息异常,重试发送导致消息重复★ 当一条消息已被成功发送到服务端并完成持久化。此时出现网络闪断或者客户端宕机,导致服务端对生产者的确认应答失败。生产者发送消息到mq时发送成功未获取到响应,然后生产者进行消息发…

信号链噪声分析18

文章目录 概要整体架构流程技术名词解释技术细节小结 概要 提示:这里可以添加技术概要 到目前为止,我们考虑的是基带采样情况,即所有目标信号均位于第一奈奎斯特区内。 图 显示了另外一种情况,其中采样信号频带局限于第一奈奎斯…

5.8.1 TCP概述

5.8.1 TCP概述 TCP是在Internet中TCP/IP协议家族中最为重要的协议之一,因特网中各种网络特性参差不齐,所以必须要有一个功能很强的互联网可靠传输协议的要求,TCP特点要与UDP特点对比来看。 UDP特点TCP特点无连接面向连接不可靠的服务可靠的…

一文详解!自动化测试如何管理测试数据

目录 前言 脚本与数据捆绑 配置文件 测试文件 数据库管理 数据平台 综述 前言 测试数据管理是自动化测试中非常重要的一环,它涉及到数据的创建、存储、维护和管理。 在之前的自动化测试框架相关文章中,无论是接口自动化还是UI自动化&#xff0c…

机器学习-支持向量机SVM

文章目录 前言1 支持向量机1.1 数据集示例11.2 带有高斯核的SVM1.2.1 高斯核1.2.2 数据集示例21.2.3 数据集示例3 2 垃圾邮件分类2.1 邮件预处理2.2 训练SVM进行垃圾邮件分类 前言 在本练习中,我们将使用支持向量机(SVM)来构建垃圾邮件分类器…

机器学习基础之《概述》

一、机器学习与人工智能、深度学习 1、机器学习是人工智能的一个实现途径 2、深度学习是机器学习的一个方法发展而来 二、统计学习和机器学习 实际机器学习在上世纪80年代已经出现,搞统计的 机器学习中有一个方法,叫人工神经网络,发展成深度…

高压线路距离保护程序逻辑原理(六)

(三)振荡与短路故障的区分 在系统发生振荡时,又发生短路故障的机率虽然不多,但万一发生应要求保护能可靠地动作于跳闸。这就要求保护能很好地区分振荡和短路故障。但是在常规距离保护中,对振荡闭锁后再发生故…

【机器学习】比较全面的XGBoost算法讲解

本文是《机器学习入门基础》(黄海广著)的第十章的部分内容。 XGBoost算法 XGBoost是2014年2月由华盛顿大学的博士生陈天奇发明的基于梯度提升算法(GBDT)的机器学习算法,其算法不但具有优良的学习效果,而且训练速度高效&#xff0c…

【软件测试】测试的分类

目录 测试的分类 1.按测试对像划分 ⭐1.界面测试 2.可靠性测试 3.容错性测试 4.文档测试 ⭐5.兼容性测试: ⭐6.易用性测试: ⭐7.安装卸载测试 ⭐8. 安全测试: ⭐9.性能测试 10.内存泄漏测试 2.按是否查看代码划分 1.黑盒测试(…

Html + Jquery + Vue前端学习笔记

文章目录 一,Vue1,v-model 数据绑定2,生成描述列表 二,HtmlJquery1,动态修改类名2,layui手风琴效果3,输入框样式修改4,多行文本显示省略号5,div内容居右6,字符…

Mysql基础教程

SELECT Company FROM Orders SQL 简介 SQL 教程SQL 语法 SQL 是用于访问和处理数据库的标准的计算机语言。 什么是 SQL? SQL 指结构化查询语言SQL 使我们有能力访问数据库SQL 是一种 ANSI 的标准计算机语言 编者注:ANSI,美国国家标准化…

HDFS之Java客户端操作

HDFS之Java客户端操作 文章目录 HDFS之Java客户端操作写在前面准备Windows关于Hadoop的开发环境下载依赖配置HADOOP_HOME环境变量配置Path环境变量 创建Maven工程XML文件创建新的Package创建HdfsClient类执行程序 HDFS的API操作 写在前面 Hadoop版本:Hadoop-3.1.3L…

CentOS忘记密码重置密码教程

文章目录 前言背景介绍:操作步骤 前言 今天打开了很久没有用过的CentOS虚拟机,然后发现我好像将所有的密码全部忘记了,根本登录不进去,最终在网找到了解决办法,这里记录一下,希望对大家有帮助 背景介绍&a…

Buildroot 取消默认QT桌面-迅为RK3588开发板

本小节将讲解如何取消掉默认的 qt 桌面。 首先对开发板进行上电,开发板正常启动后,使用命令“cd /etc/init.d”进入到/etc/init.d 目录 下,然后使用以下命令对开机自启动脚本 rcS 进行查看,如下图所示: vi rcS 从上…

机器学习优化器和SGD和SGDM实验对比(编程实现SGD和SGDM)

机器学习优化器和SGD和SGDM实验对比 博主最近在学习优化器,于是呢,就做了一个SGD和SGDM的实验对比,可谓是不做不知道,一做吓一跳,这两个算法最终对结果的影响还是挺大的,在实验中SGDM明星要比SGD效果好太多…

HHU云计算期末复习(下)Hadoop、虚拟化技术、openstack

文章目录 第五章 Hadoop分布式文件系统HDFS分离元数据和数据:NameNode和DataNode流水线复制 第七章 虚拟化技术7.1 虚拟化技术简介7.2 虚拟机迁移7.3 网络虚拟化 第八章 openstack8.1 计算服务NovaRabbitMQ 8.2 Swift 第九章 云计算数据中心9.1 云数据中心特征9.2 网…

Android firebase google登录配置流程和app内测发布流程

googlePlay使用OAuth2.0保护账号安全,且与firebase相关。如果配置错误,会出现error code比如: 10: auth,如clientId不对; 7: 网络或墙的问题; 12500:签名问题。 正确配置流程 Relea…