本文介绍如何使用Python SDK创建DNAT条目。

背景信息

本次示例分为以下几步,创建DNAT条目。
  1. 在华东2上海地域创建一个VPC。
  2. 在新建的VPC下创建一个VSwitch。
  3. 在新建的VPC下创建一个NAT网关。
  4. 在华东2上海地域创建一个EIP。
  5. 将创建的EIP绑定到NAT网关。
  6. 创建DNAT条目。
  7. 查询绑定到NAT网关的EIP。
  8. 查询NAT网关。
  9. 删除DNAT条目。
  10. 将EIP与NAT网关解绑。
  11. 删除NAT网关。
  12. 释放EIP。
  13. 删除VSwitch。
  14. 删除VPC。

操作步骤

  1. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\sdk_lib文件夹。
  2. 使用编辑器打开consts.py文件,配置用户鉴权参数ACS_CLIENT
  3. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\examples\natgw文件夹。
  4. 使用编辑器打开natgw_dnat.py文件,根据实际情况配置相关参数,保存退出。
    #encoding=utf-8
    import sys
    import json
    import time
    
    from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    from aliyunsdkvpc.request.v20160428 import CreateNatGatewayRequest
    from aliyunsdkvpc.request.v20160428 import DeleteNatGatewayRequest
    from aliyunsdkvpc.request.v20160428 import DescribeNatGatewaysRequest
    from aliyunsdkvpc.request.v20160428 import CreateForwardEntryRequest
    from aliyunsdkvpc.request.v20160428 import DescribeForwardTableEntriesRequest
    from aliyunsdkvpc.request.v20160428 import DeleteForwardEntryRequest
    from sdk_lib.sdk_vpc import Vpc
    from sdk_lib.sdk_vswitch import VSwitch
    from sdk_lib.sdk_eip import Eip
    from sdk_lib.sdk_cbwp import CommonBandwidthPackage
    from sdk_lib.common_util import CommonUtil
    from sdk_lib.check_status import CheckStatus
    from sdk_lib.exception import ExceptionHandler
    from sdk_lib.consts import *
    
    client = ACS_CLIENT
    
    
    class NatGateway(object):
        def __init__(self, client):
            self.client = client
    
        def create_nat_gateway(self, params):
            """
            create_nat_gateway: 创建NAT网关
            官网API参考: https://help.aliyun.com/document_detail/36048.html
            """
            try:
                request = CreateNatGatewayRequest.CreateNatGatewayRequest()
                request.set_VpcId(params['vpc_id'])
                response = client.do_action_with_exception(request)
                response_json = json.loads(response)
                # 判断NAT网关状态是否可用
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_nat_gateway_status,
                                            AVAILABLE, response_json['NatGatewayId']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_nat_gateway(self, nat_gateway_id):
            """
            describe_nat_gateway: 查询指定地域已创建的NAT网关的信息
            官网API参考: https://help.aliyun.com/document_detail/36054.html
            """
            try:
                request = DescribeNatGatewaysRequest.DescribeNatGatewaysRequest()
                request.set_NatGatewayId(nat_gateway_id)
                response = 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 delete_nat_gateway(self, params):
            """
            delete_nat_gateway: 删除NAT网关
            官网API参考: https://help.aliyun.com/document_detail/36051.html
            """
            try:
                request = DeleteNatGatewayRequest.DeleteNatGatewayRequest()
                request.set_NatGatewayId(params['nat_gateway_id'])
                response = client.do_action_with_exception(request)
                response_json = json.loads(response)
                # 判断NAT网关状态是否可用
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.describe_nat_gateway_status,
                                            '', params['nat_gateway_id']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_nat_gateway_status(self, nat_gateway_id):
            """
            describe_nat_gateway_status: 查询指定地域已创建的NAT网关的状态
            官网API参考: https://help.aliyun.com/document_detail/36054.html
            """
            response = self.describe_nat_gateway(nat_gateway_id)
            if len(response["NatGateways"]["NatGateway"]) == 0:
                return ''
            return response["NatGateways"]["NatGateway"][0]['Status']
    
        def create_forward_entry(self, params):
            """
            create_forward_entry: 创建forward entry
            官网API参考: https://help.aliyun.com/document_detail/36058.html
            """
            try:
                request = CreateForwardEntryRequest.CreateForwardEntryRequest()
                request.set_ForwardTableId(params['forward_table_id'])
                request.set_ExternalIp(params['external_ip'])
                request.set_IpProtocol(params['ip_protocol'])
                request.set_ExternalPort(params['external_port'])
                request.set_InternalIp(params['internal_ip'])
                request.set_InternalPort(params['internal_port'])
                response = client.do_action_with_exception(request)
                response_json = json.loads(response)
                # 判断Forward Entry状态是否可用
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_forward_status,
                                            AVAILABLE, params['forward_table_id']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
        def describe_forward(self, forward_table_id):
            """
            describe_forward: 查询指定地域已创建的dnat的信息
            官网API参考: https://help.aliyun.com/document_detail/36053.html
            """
            try:
                request = DescribeForwardTableEntriesRequest.DescribeForwardTableEntriesRequest()
                request.set_ForwardTableId(forward_table_id)
                response = 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_forward_status(self, forward_table_id):
            """
            describe_forward_status: 查询指定地域已创建的dnat的状态
            官网API参考: https://help.aliyun.com/document_detail/36053.html
            """
            response = self.describe_forward(forward_table_id)
            if len(response["ForwardTableEntries"]["ForwardTableEntry"]) == 0:
                return ''
            return response["ForwardTableEntries"]["ForwardTableEntry"][0]['Status']
    
        def delete_forward_entry(self, params):
            """
            delete_forward_entry: 删除forward entry
            官网API参考: https://help.aliyun.com/document_detail/36050.html
            """
            try:
                request = DeleteForwardEntryRequest.DeleteForwardEntryRequest()
                request.set_ForwardTableId(params['forward_table_id'])
                request.set_ForwardEntryId(params['forward_entry_id'])
                response = client.do_action_with_exception(request)
                response_json = json.loads(response)
                # 判断Forward Entry状态是否可用
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME * 5,
                                            self.describe_forward_status,
                                            '', params['forward_table_id']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
    
    
    def main():
        vpc = Vpc(client)
        vswitch = VSwitch(client)
        eip = Eip(client)
        cbwp = CommonBandwidthPackage(client)
        nat_gateway = NatGateway(client)
    
        params = {}
    
        # 创建vpc
        vpc_json = vpc.create_vpc()
        CommonUtil.log("create_vpc", vpc_json)
    
        # 创建vswitch
        params['vpc_id'] = vpc_json['VpcId']
        params['zone_id'] = "cn-shanghai-b"
        params['cidr_block'] = "172.16.1.0/24"
        vswitch_json = vswitch.create_vswitch(params)
        CommonUtil.log("create_vswitch", vswitch_json)
        params['vswitch_id'] = vswitch_json['VSwitchId']
    
        # 创建Nat网关
        nat_gateway_json = nat_gateway.create_nat_gateway(params)
        CommonUtil.log("create_nat_gateway", nat_gateway_json)
    
        # 创建EIP
        eip_response_json = eip.allocate_eip_address(params)
        CommonUtil.log("allocate_eip_address", eip_response_json)
        params['allocation_id'] = eip_response_json["AllocationId"]
        params['external_ip'] = eip_response_json['EipAddress']
    
        # 绑定EIP到NAT网关
        params['instance_id'] = nat_gateway_json['NatGatewayId']
        params['allocation_id'] = eip_response_json["AllocationId"]
        params['instance_type'] = 'Nat'
        eip_response_json = eip.associate_eip_address(params)
        CommonUtil.log("associate_eip_address eip", eip_response_json)
    
        # 创建DNAT条目
        params['forward_table_id'] = nat_gateway_json['ForwardTableIds']['ForwardTableId'][0]
        params['ip_protocol'] = 'tcp'
        params['external_port'] = '8080'
        params['internal_port'] = '80'
        params['internal_ip'] = '172.16.1.0'
        forward_entry_json = nat_gateway.create_forward_entry(params)
        CommonUtil.log("create_forward_entry", forward_entry_json)
    
        # 查询EIP
        eip_response_json = eip.describe_eip_address(params['allocation_id'])
        CommonUtil.log("describe_eip_address", eip_response_json)
    
        # 查询Nat网关
        params['nat_gateway_id'] = nat_gateway_json['NatGatewayId']
        nat_gateway_json = nat_gateway.describe_nat_gateway(params['nat_gateway_id'])
        CommonUtil.log("describe_nat_gateway", nat_gateway_json)
    
        # 删除DNAT条目
        params['forward_entry_id'] = forward_entry_json['ForwardEntryId']
        forward_entry_json = nat_gateway.delete_forward_entry(params)
        CommonUtil.log("delete_forward_entry", forward_entry_json)
    
        # 解绑EIP
        eip_response_json = eip.unassociate_eip_address(params)
        CommonUtil.log("unassociate_eip_address nat", eip_response_json)
    
        # 删除Nat网关
        nat_gateway_json = nat_gateway.delete_nat_gateway(params)
        CommonUtil.log("delete_nat_gateway", nat_gateway_json)
    
        # 释放EIP
        eip_response_json = eip.release_eip_address(params)
        CommonUtil.log("release_eip_address", eip_response_json)
    
        # 删除vswitch
        params['vswitch_id'] = vswitch_json['VSwitchId']
        vswitch_json = vswitch.delete_vswitch(params)
        CommonUtil.log("delete_vswitch", vswitch_json)
    
        # 删除vpc
        vpc_json = vpc.delete_vpc(params)
        CommonUtil.log("delete_vpc", vpc_json)
    
    
    if __name__ == "__main__":
        sys.exit(main())
  5. 进入natgw_dnat.py所在的目录,执行如下命令,创建DNAT条目。
    python natgw_dnat.py
    系统显示类似如下:
    ---------------------------create_vpc---------------------------
    {
      "ResourceGroupId": "rg-acfmxazxxxxxxxx",
      "RouteTableId": "vtb-uf63rln6gbb50xxxxxxxx",
      "VRouterId": "vrt-uf6p1hfo0ho8gxxxxxxxx",
      "VpcId": "vpc-uf6c3r8yca7dhxxxxxxxx",
      "RequestId": "1F97FC59-77DF-4D76-BE62-0A13EB4E614C"
    }
    
    ---------------------------create_vswitch---------------------------
    {
      "VSwitchId": "vsw-uf6liy66d9ssuxxxxxxxx",
      "RequestId": "88CCCFED-1448-49D2-8550-71952981A47A"
    }
    
    ---------------------------create_nat_gateway---------------------------
    {
      "NatGatewayId": "ngw-uf6aolgwhssvsxxxxxxxx",
      "BandwidthPackageIds": {
        "BandwidthPackageId": []
      },
      "ForwardTableIds": {
        "ForwardTableId": [
          "ftb-uf6unjiun4i12xxxxxxxx"
        ]
      },
      "RequestId": "62A58351-D608-43A4-849E-1E177E917BEA",
      "SnatTableIds": {
        "SnatTableId": [
          "stb-uf65utljwcdkpxxxxxxxx"
        ]
      }
    }
    
    ---------------------------allocate_eip_address---------------------------
    {
      "EipAddress": "101.xx.xx.110",
      "ResourceGroupId": "rg-acfmxazxxxxxxxx",
      "RequestId": "0565295E-2F49-4511-93BC-747A2D19A6BD",
      "AllocationId": "eip-uf683xrl32ge8xxxxxxxx"
    }
    
    ---------------------------associate_eip_address eip---------------------------
    {
      "RequestId": "8759FCE8-F8C2-4372-91D5-7A25D43FD78C"
    }
    
    ---------------------------create_forward_entry---------------------------
    {
      "ForwardEntryId": "fwd-uf6ng3wt8sfwmxxxxxxxx",
      "RequestId": "CC81BCF6-2F64-40CF-85B0-676A83AC3902"
    }
    
    ---------------------------describe_eip_address---------------------------
    {
      "TotalCount": 1,
      "PageNumber": 1,
      "PageSize": 10,
      "EipAddresses": {
        "EipAddress": [
          {
            "ISP": "BGP",
            "ExpiredTime": "",
            "InternetChargeType": "PayByBandwidth",
            "IpAddress": "101.xx.xx.110",
            "AllocationId": "eip-uf683xrl32ge8xxxxxxxx",
            "PrivateIpAddress": "",
            "Status": "InUse",
            "BandwidthPackageId": "",
            "InstanceId": "ngw-uf6aolgwhssvsxxxxxxxx",
            "InstanceRegionId": "cn-shanghai",
            "RegionId": "cn-shanghai",
            "AvailableRegions": {
              "AvailableRegion": [
                "cn-shanghai"
              ]
            },
            "ResourceGroupId": "rg-acfmxazxxxxxxxx",
            "HasReservationData": false,
            "InstanceType": "Nat",
            "AllocationTime": "2019-04-24T10:56:53Z",
            "Name": "",
            "OperationLocks": {
              "LockReason": []
            },
            "Mode": "NAT",
            "BandwidthPackageType": "",
            "BandwidthPackageBandwidth": "",
            "Bandwidth": "5",
            "HDMonitorStatus": "OFF",
            "ChargeType": "PostPaid",
            "SecondLimited": false,
            "Descritpion": ""
          }
        ]
      },
      "RequestId": "CD2B3613-2A99-4687-9C23-A8E9F1F03048"
    }
    
    ---------------------------describe_nat_gateway---------------------------
    {
      "TotalCount": 1,
      "PageNumber": 1,
      "RequestId": "D7519663-8D3B-4CC5-894F-A6798C89688D",
      "PageSize": 10,
      "NatGateways": {
        "NatGateway": [
          {
            "Status": "Available",
            "BandwidthPackageIds": {
              "BandwidthPackageId": []
            },
            "VpcId": "vpc-uf6c3r8yca7dhxxxxxxxx",
            "Description": "",
            "ForwardTableIds": {
              "ForwardTableId": [
                "ftb-uf6unjiun4i12xxxxxxxx"
              ]
            },
            "IpLists": {
              "IpList": [
                {
                  "UsingStatus": "UsedByForwardTable",
                  "IpAddress": "101.xx.xx.110",
                  "AllocationId": "eip-uf683xrl32ge8xxxxxxxx"
                }
              ]
            },
            "BusinessStatus": "Normal",
            "RegionId": "cn-shanghai",
            "CreationTime": "2019-04-24T10:56:50Z",
            "NatGatewayId": "ngw-uf6aolgwhssvsxxxxxxxx",
            "SnatTableIds": {
              "SnatTableId": [
                "stb-uf65utljwcdkpxxxxxxxx"
              ]
            },
            "AutoPay": false,
            "InstanceChargeType": "PostPaid",
            "ExpiredTime": "",
            "Spec": "Small",
            "Name": ""
          }
        ]
      }
    }
    
    ---------------------------delete_forward_entry---------------------------
    {
      "RequestId": "32C76D08-5738-4B07-A638-ACE5F5F5220E"
    }
    
    ---------------------------unassociate_eip_address nat--------------------------
    -
    {
      "RequestId": "AE686920-2CD1-4850-AADC-C249484D4B1A"
    }
    
    ---------------------------delete_nat_gateway---------------------------
    {
      "RequestId": "FEBB1E7A-BA5B-4445-B2AB-5B828C17BBE6"
    }
    
    ---------------------------release_eip_address---------------------------
    {
      "RequestId": "812D5E78-5113-4B92-892D-0B293BAD66F6"
    }
    
    ---------------------------delete_vswitch---------------------------
    {
      "RequestId": "8E13EEE4-21B5-4280-B46B-5C168736DC3A"
    }
    
    ---------------------------delete_vpc---------------------------
    {
      "RequestId": "DCBA91E7-F355-4EB6-83E3-27F2E68A8435"
    }