1. 程式人生 > 其它 >python 呼叫api 虛擬私有云子網管理

python 呼叫api 虛擬私有云子網管理

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"]))