from HwUser import HwUser
import json
import time
'''
在云服务器的/root/huawei 目录下编写 create_subnet.py 文件, 并导入赛项提供的HwUser.py 文件获取授权。编写 Python 代码,参考官方相关的API调用文档,创建华为云的虚拟私有云子网,具体要求为
(1)使用虚拟私有云名称获取其 ID(不允许直接填写虚拟私有云 ID);
(2)虚拟私有云子网名称:chinaskills_subnet;
(3)虚拟私有云子网网段:192.168.100.0/24;
(4)虚拟私有云子网网关:192.168.100.1;
(5)虚拟私有云子网可用区域:cn-north-4a;
(6)如果虚拟私有云子网已经存在,代码中需要先删除;
(7)使用其源码的 get 方法输出此虚拟私有云子网的详细信息(状态要求为 ACTIVE)。
'''
if __name__ == "__main__":
# 1 获取授权
ak = "7IJFH088K7ZHG6H7MJ7E"
sk = "ClkPa47PpNxEpiPzKQ3c5Nzcb1S5uSVGhQ13owge"
user = HwUser(ak, sk)
# 2 查询VPC
print("正在查询vpc。。。。", end="")
resp = user.httpRequest("GET", "https://vpc.cn-east-2.myhuaweicloud.com/v3/0f4115bb9280f3192fa7c00e1c434035/vpc/vpcs")
result = json.loads(str(resp.content, encoding="utf-8"))
## 2.1 查看是否已存在VPC chinaskills_vpc
### 取出现有的VPC 列表
now_vpc_list = result["vpcs"]
targetID = ""
for i in now_vpc_list:
if "chinaskills_vpc" == i["name"]:
targetID = i["id"]
if targetID == "":
exit("当前环境未存在 chinaskills_vpc")
else:
print(" 正在查询 chinaskills_vpc 中子网是否存在。。。")
### 查看子网信息
requestURL = "https://vpc.cn-east-2.myhuaweicloud.com/v1/0f4115bb9280f3192fa7c00e1c434035/subnets?vpc_id="+targetID
resp = user.httpRequest("GET", requestURL,{ "content-type": "application/json" },"")
result = json.loads(str(resp.content, encoding="utf-8"))
now_vpc_subnet_list = result["subnets"]
subnets = []
for i in now_vpc_subnet_list:
if "chinaskills_subnet" == i["name"]:
### 删除子网
requestURL = "https://vpc.cn-east-2.myhuaweicloud.com/v1/0f4115bb9280f3192fa7c00e1c434035/vpcs/"+targetID+"/subnets/"+i["id"]
resp = user.httpRequest("DELETE", requestURL,{ "content-type": "application/json" },"")
print(" 删除完成")
# 3 创建subnet
print("正在创建subnet。。。。", end="")
time.sleep(2)
requestURL = "https://vpc.cn-east-2.myhuaweicloud.com/v1/0f4115bb9280f3192fa7c00e1c434035/subnets"
bodys=json.dumps({
"subnet": {
"name": "chinaskills_subnet",
"cidr": "192.168.100.0/24",
"vpc_id": targetID,
"gateway_ip": "192.168.100.1",
"extra_dhcp_opts": [
{
"opt_name": "ntp"
}
]
}
})
resp = user.httpRequest("POST", requestURL,{ "content-type": "application/json" },bodys)
## 3.1 获取ID
result = json.loads(str(resp.content, encoding="utf-8"))
yid = result["subnet"]["id"]
print("完成,新subnet ID为:"+yid)
# 4 查询
print("Subnet信息查询中。。。")
time.sleep(2)
requestURL = "https://vpc.cn-east-2.myhuaweicloud.com/v1/0f4115bb9280f3192fa7c00e1c434035/subnets/"+yid
resp = user.httpRequest("GET", requestURL, { "content-type": "application/json" }, "")
result = json.loads(str(resp.content, encoding="utf-8"))
print(" subnet name:"+str(result["subnet"]["name"]))
print(" subnet id:"+str(result["subnet"]["id"]))
print(" subnet status:"+str(result["subnet"]["status"]))