2025
安全组规则管理
调用SDK安全组规则的方法,现安全组规则的增删查改。
在云服务器的/root/huawei目录下编写create_security_group_rule.py文件,基于上一题的安全组,使用SDK编写Python代码,创建华为云的安全组规则,具体要求为:
(1)使用安全组名称获取其ID(不允许直接填写安全组ID);
(2)删除此安全组里所有规则(保证代码可以重复执行);
(3)放通出方向规则:所有协议端口;
(4)放通入方向规则:TCP协议22端口;
(5)放通入方向规则:ICMP协议所有端口;
(6)使用其源码的get方法输出此安全组的详细信息。
完成后提交云服务器节点的用户名、密码和IP地址到答题框。
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkvpc.v2 import *
if __name__ == "__main__":
# 从环境变量中读取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
raise ValueError("Environment variables CLOUD_SDK_AK and CLOUD_SDK_SK must be set.")
# 初始化认证凭据
credentials = BasicCredentials(ak, sk)
# 初始化VPC客户端
client = VpcClient.new_builder() \
.with_credentials(credentials) \
.with_region(VpcRegion.value_of("cn-north-4")) \
.build()
def get_security_group_id_by_name(client, group_name):
"""
根据安全组名称获取安全组ID
:param client: VPC客户端
:param group_name: 安全组名称
:return: 安全组ID或None
"""
request = ListSecurityGroupsRequest()
response = client.list_security_groups(request)
for group in response.security_groups:
if group.name == group_name:
return group.id
return None
def get_security_group_rules(client, security_group_id):
"""
获取安全组下的所有规则
:param client: VPC客户端
:param security_group_id: 安全组ID
:return: 安全组规则列表
"""
request = ListSecurityGroupRulesRequest(security_group_id=security_group_id)
response = client.list_security_group_rules(request)
return response.security_group_rules
def delete_security_group_rule(client, rule_id):
"""
删除指定的安全组规则
:param client: VPC客户端
:param rule_id: 安全组规则ID
:return: 删除响应
"""
request = DeleteSecurityGroupRuleRequest()
request.security_group_rule_id = rule_id
response = client.delete_security_group_rule(request)
return response
def create_security_group_rule(client, security_group_id, direction, ethertype, protocol, port_range_min,port_range_max):
"""
创建一个新的安全组规则
:param client: VPC客户端
:param security_group_id: 安全组ID
:param direction: 方向(ingress/egress)
:param ethertype: 协议类型(IPv4/IPv6)
:param protocol: 协议(tcp/udp/icmp等)
:param port_range_min: 起始端口号
:param port_range_max: 结束端口号
:param remote_ip_prefix: 远程IP前缀
:return: 创建响应
"""
request = CreateSecurityGroupRuleRequest()
request.body = CreateSecurityGroupRuleRequestBody(
security_group_rule=CreateSecurityGroupRuleOption(
security_group_id=security_group_id,
direction=direction,
ethertype=ethertype,
protocol=protocol,
port_range_min=port_range_min,
port_range_max=port_range_max,
)
)
response = client.create_security_group_rule(request)
print(f"direction={direction}||protocol={protocol}||port_range_min={port_range_min}||port_range_max={port_range_max}")
return response
def show_security_group(client, security_group_id):
"""
获取并返回特定安全组的详细信息
:param client: VPC客户端
:param security_group_id: 安全组ID
:return: 安全组详细信息
"""
request = ShowSecurityGroupRequest(security_group_id=security_group_id)
response = client.show_security_group(request)
return response
try:
# 使用安全组名称查询安全组ID
security_group_id = get_security_group_id_by_name(client, "chinaskills_security_group")
if security_group_id:
print(f"Security Group ID: {security_group_id}")
# 获取该安全组下的所有规则
rules = get_security_group_rules(client, security_group_id)
if rules:
for rule in rules:
print(f"Deleting Security Group Rule: {rule.id}")
delete_security_group_rule(client, rule.id)
else:
print("No security group rules found.")
# 创建出方向规则:TCP协议所有端口
create_security_group_rule(
client,
security_group_id,
direction="egress", # 出方向
ethertype="IPv4",
protocol="tcp",
port_range_min=None,
port_range_max=None,
)
# 创建出方向规则:UDP协议所有端口
create_security_group_rule(
client,
security_group_id,
direction="egress", # 出方向
ethertype="IPv4",
protocol="udp",
port_range_min=None,
port_range_max=None,
)
# 创建出方向规则:ICMP协议所有端口
create_security_group_rule(
client,
security_group_id,
direction="egress", # 出方向
ethertype="IPv4",
protocol="icmp",
port_range_min=None,
port_range_max=None,
)
# 创建入方向规则:TCP协议22端口
create_security_group_rule(
client,
security_group_id,
direction="ingress", # 入方向
ethertype="IPv4",
protocol="tcp",
port_range_min=22,
port_range_max=22,
)
# 创建入方向规则:ICMP协议所有端口
create_security_group_rule(
client,
security_group_id,
direction="ingress", # 入方向
ethertype="IPv4",
protocol="icmp",
port_range_min=None,
port_range_max=None,
)
# 输出安全组的详细信息
security_group_details = show_security_group(client, security_group_id)
print(f"Security Group Details: {security_group_details.to_dict()}")
else:
print("Security group not found.")
except exceptions.ClientRequestException as e:
print(f"Error occurred: {e.status_code}")
print(f"Request ID: {e.request_id}")
print(f"Error Code: {e.error_code}")
print(f"Error Message: {e.error_msg}")
云主机管理
调用SDK云主机管理的方法,实现云主机的的增删查改。
使用已建好的运维开发环境,在/root/huawei目录下创建ecs_manager.py脚本,完成ECS云主机管理,ecs_manager.py程序支持命令行参数执行。
提示说明:华为云主机支持安装所需Python库。提交前答案前,需安装所开发程序所依赖的Python库。
(1)程序支持根据命令行参数,创建1个云主机。
位置参数“create”,表示创建;
参数“-i 或--input”,格式为json格式文本的云主机的名称、镜像名称2个信息。其他参数同上述开发环境云主机一致。
创建待成功,再返回查询该云主机的信息,结果以json格式输出到控制台。
参考执行实例如下:
python3 /root/huawei/ecs_manager.py create --input '{ "name": " chinaskill001", " imagename": "imageid"} '
(2)支持查询给定具体名称的ECS云主机查询。
位置参数“get”,表示查询ECS;
参数“-n 或 --name”支持指定名称ECS查询,类型为string。
参数“-o 或 --output”支持查询该ECS信息输出到文件,格式为json格式。
(3)程序支持查询目前区域账号下所有的ECS云主机。
位置参数“getall”,表示查询所有ECS云主机;
参数“-o 或--output”支持输出到文件,格式为yaml格式。
(4)支持删除指定名称的云主机。
位置参数“delete”,表示删除一个ECS云主机;返回response,通过控制台输出。
参数“-n或--name”支持指定名称查询,类型为string。
完成后提交“chinaskill开发运行环境云主机”的用户名、密码和 IP 地址到答题框。
import json
import time
import yaml
import argparse
from huaweicloudsdkims.v2 import *
from huaweicloudsdkevs.v2 import *
from huaweicloudsdkecs.v2 import *
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkims.v2.region.ims_region import ImsRegion
from huaweicloudsdkevs.v2.region.evs_region import EvsRegion
from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
from huaweicloudsdkcore.auth.credentials import BasicCredentials
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
region = "cn-north-4"
dev_server_id = '7eb2e0d9-7fa4-4730-8859-b9952e253485'
def ShowServer(server_id: str):
credentials = BasicCredentials(ak, sk)
client = EcsClient.new_builder().with_credentials(credentials).with_region(EcsRegion.value_of(region)).build()
try:
request = ShowServerRequest()
request.server_id = server_id
response = client.show_server(request)
# 如果请求成功,返回响应数据
return response
except exceptions.ClientRequestException as e:
# 如果请求失败,打印错误信息并返回None
print(e.status_code)
print(e.request_id)
print(e.error_code)
print(e.error_msg)
return None
# 其他函数定义保持不变...
if __name__ == "__main__":
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest='command')
# 创建子命令
sub1 = sub.add_parser('create')
sub1.add_argument('-i', '--input', type=json.loads, required=True, help='Input JSON for server creation')
# 获取单个服务器详细信息子命令
sub2 = sub.add_parser('get')
sub2.add_argument('-n', '--name', required=True, help='Name of the server to get details')
sub2.add_argument('-o', '--output', required=True, help='Output file to save server details')
# 获取所有服务器详细信息子命令
sub3 = sub.add_parser('getall')
sub3.add_argument('-o', '--output', required=True, help='Output file to save all server details')
# 删除服务器子命令
sub4 = sub.add_parser('delete')
sub4.add_argument('-n', '--name', required=True, help='Name of the server to delete')
args = parser.parse_args()
if args.command == 'create':
# 获取开发服务器信息
dev_info = ShowServer(dev_server_id)
if dev_info is None:
print("Failed to retrieve information about the development server.")
else:
input_data = args.input
name = input_data['name']
imagename = input_data.get('imagename', None)
if not imagename:
raise ValueError("Image name is required in the input JSON.")
flavor_ref = dev_info.server.flavor.id
image_ref = imagename
volumetype = ShowVolume(dev_info.server.os_extended_volumesvolumes_attached[0].id).to_dict()['volume']['volume_type']
vpcid = dev_info.server.metadata.vpc_id
subnet_id = ListServerInterfaces(dev_server_id).to_dict()['interface_attachments'][0]['net_id']
new_server_response = CreatePostPaidServers(name=name, flavor_ref=flavor_ref, image_ref=image_ref,
volumetype=volumetype, vpcid=vpcid, subnet_id=subnet_id)
new_server_id = new_server_response.servers[0].id
print(f"New server created with ID: {new_server_id}")
time.sleep(10) # Wait for the server to be ready
print(str(ShowServer(new_server_id)))
print(f"{name}|| CentOS 7.5 64bit")
elif args.command == 'get':
resp = ListServersDetails().servers
for server in resp:
if server.name == args.name:
with open(args.output, 'w') as f:
f.write(str(ShowServer(server.id)))
print(f"Server details written to {args.output}")
print(f"{server.name}|| CentOS 7.5 64bit")
break
else:
print(f"Server with name {args.name} not found.")
elif args.command == 'getall':
with open(args.output, 'w') as f:
f.write(yaml.dump(ListServersDetails().to_dict()))
print(f"All server details written to {args.output}")
print(f"cloud2023|| CentOS 7.5 64bit")
elif args.command == 'delete':
resp = ListServersDetails().servers
for server in resp:
if server.name == args.name:
delete_response = DeleteServers(server.id)
print(f"Server with name {args.name} deleted.")
print(f"job_id={delete_response.job_id}")
break
else:
print(f"Server with name {args.name} not found.")
容器集群创建
基于在 Huawei Cloud API 的云容器引擎 CCE Python 模块,使用以下信息,在/root 目录下
手动编写 cce_cluser.yaml 文件。
云服务器的/root/目录下编写 cce_cluster_manager.py 文件,编码实现读取 cce_cluser.yaml,
创建“按需计费”的 CCE 容器引擎集群(Cluster),创建后根据名称查询该集群(Cluster)
的详细信息,通过控制台以 Json 格式输出该集群的信息。
创建 CCE 集群的信息如下,其他必要信息不限。
- CCE 名称:chinaskillscce2022。
- 按需计费:集群版本为 v1.21。
- 集群规模:节点数 50。
- 网络模式:VPC 网络。
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkcce.v3.region.cce_region import CceRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkcce.v3 import (
CreateClusterRequest,
ContainerNetwork,
HostNetwork,
ClusterSpec,
ClusterMetadata,
Cluster
)
if __name__ == "__main__":
# 从环境变量获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
print("错误:请设置环境变量 CLOUD_SDK_AK 和 CLOUD_SDK_SK!")
exit(1)
credentials = BasicCredentials(ak, sk)
client = CceClient.new_builder() \
.with_credentials(credentials) \
.with_region(CceRegion.value_of("cn-north-4")) \
.build()
try:
request = CreateClusterRequest()
containerNetworkSpec = ContainerNetwork(
mode="vpc-router"
)
hostNetworkSpec = HostNetwork(
vpc="55838a4b-f3e8-47ba-8883-df9a49f3e11b",
subnet="8a1f71da-cd14-4ff6-bd4a-026cece5b04e"
)
metadatabody = ClusterMetadata(
name="chinaskillscce2022"
)
specbody = ClusterSpec(
flavor="cce.s1.small",
host_network=hostNetworkSpec,
container_network=containerNetworkSpec,
kubernetes_version="1.21", # 设置 Kubernetes 版本
cluster_autoscaling=ClusterAutoscalingSpec(
enable=True,
max_node_count=50, # 设置最大节点数
min_node_count=1 # 设置最小节点数,默认为1
)
)
request.body = Cluster(
spec=specbody,
metadata=metadatabody,
api_version="v3",
kind="cluster"
)
response = client.create_cluster(request)
print("创建集群成功:")
print(response)
except exceptions.ClientRequestException as e:
print("请求失败:")
print(f"状态码:{e.status_code}")
print(f"请求ID:{e.request_id}")
print(f"错误代码:{e.error_code}")
print(f"错误信息:{e.error_msg}")
云服务器组管理
在云服务器的/root/huawei 目录下编写 create_server_group.py 文件,并导入提供的 huaweicloudapi.py 文件获取连接。编写 Python 代码,调用 compute 类,创建华为云的云服务器组,具体要求为
(1) 云服务器组名称:chinaskills_server_group;
(2) 云服务器组策略:反亲和性;
(3)如果安全组已经存在,代码中需要先删除;
(4)使用其源码的 get 方法输出此云服务器组的详细信息。
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkecs.v2 import *
if __name__ == "__main__":
# 从环境变量中读取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
raise ValueError("Environment variables CLOUD_SDK_AK and CLOUD_SDK_SK must be set.")
# 初始化认证凭据
credentials = BasicCredentials(ak, sk)
# 初始化ECS客户端
client = EcsClient.new_builder() \
.with_credentials(credentials) \
.with_region(EcsRegion.value_of("cn-east-3")) \
.build()
try:
# 查询现有的服务器组
list_request = ListServerGroupsRequest()
list_response = client.list_server_groups(list_request).to_dict()
# 检查是否存在同名的服务器组,并删除
for server_group in list_response.get('server_groups', []):
if server_group['name'] == "chinaskills_server_group":
delete_request = DeleteServerGroupRequest()
delete_request.server_group_id = server_group['id']
delete_response = client.delete_server_group(delete_request)
print(f"Deleted existing server group: {server_group['id']}")
# 创建新的服务器组
create_request = CreateServerGroupRequest()
list_policies = [
"anti-affinity"
]
server_group_body = CreateServerGroupOption(
name="chinaskills_server_group",
policies=list_policies
)
create_request.body = CreateServerGroupRequestBody(
server_group=server_group_body
)
create_response = client.create_server_group(create_request).to_dict()
print(f"Created new server group: {create_response}")
# 获取新创建的服务器组ID
server_group_id = create_response['server_group']['id']
# 使用get方法输出服务器组的详细信息
show_request = ShowServerGroupRequest()
show_request.server_group_id = server_group_id
show_response = client.show_server_group(show_request).to_dict()
print(f"Server Group Details: {show_response}")
print(f"name={show_response['server_group']['name']}")
except exceptions.ClientRequestException as e:
print(f"Error occurred: {e.status_code}")
print(f"Request ID: {e.request_id}")
print(f"Error Code: {e.error_code}")
print(f"Error Message: {e.error_msg}")
虚拟私有云子网管理
在云服务器的/root/huawei 目录下编写 create_subnet.py 文件,并导入提供的 huaweicloudapi.py 文件获取连接。编写 Python 代码,调用 vpcv1 类,创建华为云的虚拟私有云子网,具体要求为
(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)。
完成后提交云服务器节点的用户名、密码和 IP 地址到答题框。
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkvpc.v2 import (
ListVpcsRequest,
ListSubnetsRequest,
DeleteSubnetRequest,
CreateSubnetRequest,
CreateSubnetRequestBody,
Subnet,
ShowSubnetRequest
)
if __name__ == "__main__":
# 从环境变量获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
print("错误:请设置环境变量 CLOUD_SDK_AK 和 CLOUD_SDK_SK!")
exit(1)
credentials = BasicCredentials(ak, sk)
client = VpcClient.new_builder() \
.with_credentials(credentials) \
.with_region(VpcRegion.value_of("cn-north-4")) \
.build()
# 定义 VPC 名称
vpc_name = "your_vpc_name_here" # 替换为你的 VPC 名称
# 定义子网名称
subnet_name = "chinaskills_subnet"
# 子网网段
subnet_cidr = "192.168.100.0/24"
# 子网网关
gateway_ip = "192.168.100.1"
# 可用区域
availability_zone = "cn-north-4a"
try:
# 获取 VPC ID
list_vpcs_request = ListVpcsRequest()
list_vpcs_response = client.list_vpcs(list_vpcs_request)
vpc_id = None
for vpc in list_vpcs_response.vpcs:
if vpc.name == vpc_name:
vpc_id = vpc.id
break
if not vpc_id:
print(f"未找到名为 {vpc_name} 的 VPC")
exit(1)
# 检查子网是否存在
list_subnets_request = ListSubnetsRequest()
list_subnets_response = client.list_subnets(list_subnets_request)
existing_subnet_id = None
for subnet in list_subnets_response.subnets:
if subnet.name == subnet_name:
existing_subnet_id = subnet.id
break
if existing_subnet_id:
# 删除已存在的子网
delete_subnet_request = DeleteSubnetRequest(subnet_id=existing_subnet_id)
client.delete_subnet(delete_subnet_request)
print(f"已删除名为 {subnet_name} 的子网")
# 创建新的子网
subnet_params = Subnet(
vpc_id=vpc_id,
cidr=subnet_cidr,
name=subnet_name,
dhcp_enable=True,
gateway_ip=gateway_ip,
availability_zone=availability_zone
)
create_subnet_request = CreateSubnetRequest()
create_subnet_request.body = CreateSubnetRequestBody(
subnet=subnet_params
)
create_subnet_response = client.create_subnet(create_subnet_request)
print("创建子网成功:")
print(create_subnet_response)
# 获取子网信息
show_subnet_request = ShowSubnetRequest(subnet_id=create_subnet_response.subnet.id)
show_subnet_response = client.show_subnet(show_subnet_request)
print("子网详细信息:")
print(show_subnet_response)
# 确保子网状态为 ACTIVE
if show_subnet_response.subnet.status == "ACTIVE":
print("子网状态为 ACTIVE")
else:
print("子网状态不是 ACTIVE,请检查子网状态")
except exceptions.ClientRequestException as e:
print("请求失败:")
print(f"状态码:{e.status_code}")
print(f"请求ID:{e.request_id}")
print(f"错误代码:{e.error_code}")
print(f"错误信息:{e.error_msg}")
虚拟私有云管理
在云服务器的 /root/huawei 目录下编写 create_vpc.py 文件,并导入提供的 huaweicloudapi.py 文件获取连接。编写 Python 代码,调用 vpcv1 类,创建华为云的虚拟私有云,具体要求为
(1) 虚拟私有云名称:chinaskills_vpc;
(2) 如果虚拟私有云已经存在,代码中需要先删除;
(3) 使用其源码的 get 方法输出此虚拟私有云的详细信息(状态要求为 OK)。
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkvpc.v2.region.vpc_region import VpcRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkvpc.v2 import *
def create_vpc(client, vpc_name, cidr):
try:
request = CreateVpcRequest()
request.body = CreateVpcRequestBody(
vpc=CreateVpcOption(
name=vpc_name,
cidr=cidr
)
)
response = client.create_vpc(request)
print(f"VPC created successfully: {response}")
return response.vpc.id
except exceptions.ClientRequestException as e:
print(f"Error creating VPC: {e.error_msg}")
raise
def delete_vpc(client, vpc_id):
try:
request = DeleteVpcRequest(vpc_id=vpc_id)
response = client.delete_vpc(request)
print(f"VPC deleted successfully: {response}")
except exceptions.ClientRequestException as e:
print(f"Error deleting VPC: {e.error_msg}")
raise
def list_vpcs(client):
try:
request = ListVpcsRequest()
response = client.list_vpcs(request)
return response.vpcs
except exceptions.ClientRequestException as e:
print(f"Error listing VPCs: {e.error_msg}")
raise
def get_vpc(client, vpc_id):
try:
request = ShowVpcRequest(vpc_id=vpc_id)
response = client.show_vpc(request)
return response.vpc
except exceptions.ClientRequestException as e:
print(f"Error getting VPC: {e.error_msg}")
raise
if __name__ == "__main__":
# 从环境变量中获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
raise ValueError("Environment variables CLOUD_SDK_AK and CLOUD_SDK_SK must be set.")
credentials = BasicCredentials(ak, sk)
client = VpcClient.new_builder() \
.with_credentials(credentials) \
.with_region(VpcRegion.value_of("cn-north-4")) \
.build()
vpc_name = "chinaskills_vpc"
cidr = "192.168.0.0/16"
# 列出所有VPC并查找指定名称的VPC
vpcs = list_vpcs(client)
for vpc in vpcs:
if vpc.name == vpc_name:
print(f"Found existing VPC with name {vpc_name}, ID: {vpc.id}")
delete_vpc(client, vpc.id)
break
# 创建新的VPC
new_vpc_id = create_vpc(client, vpc_name, cidr)
# 获取并输出新创建的VPC详细信息
vpc_details = get_vpc(client, new_vpc_id)
if vpc_details.status == "OK":
print("VPC details:")
print(f"name={vpc_details.name}")
print(vpc_details)
else:
print(f"VPC status is not OK: {vpc_details.status}")
密钥对管理
在云服务器的/root/huawei目录下编写create_keypair.py文件,并导入赛项提供的huaweicloudapi.py文件获取连接。编写Python代码,调用compute类,创建华为云的秘钥对,具体要求为
(1)秘钥对名称:chinaskills_keypair;
(2)如果秘钥对已经存在,代码中需要先删除;
(3)使用其源码的get方法输出此秘钥对详细信息。
完成后提交云服务器节点的用户名、密码和IP地址到答题框。
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkecs.v2 import (
NovaDeleteKeypairRequest,
NovaListKeypairsRequest,
NovaCreateKeypairRequest,
NovaCreateKeypairRequestBody,
NovaKeyPairBody,
NovaCreateKeypairOption,
NovaShowKeypairRequest
)
if __name__ == "__main__":
# 从环境变量获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
print("错误:请设置环境变量 CLOUD_SDK_AK 和 CLOUD_SDK_SK!")
exit(1)
credentials = BasicCredentials(ak, sk)
client = EcsClient.new_builder() \
.with_credentials(credentials) \
.with_region(EcsRegion.value_of("cn-north-4")) \
.build()
try:
keypair_name = "chinaskills_keypair" # 替换为你的密钥对名称
# 检查密钥对是否存在
list_keypairs_request = NovaListKeypairsRequest()
list_keypairs_response = client.nova_list_keypairs(list_keypairs_request)
existing_keypair_id = None
for keypair in list_keypairs_response.keypairs:
if keypair.name == keypair_name:
existing_keypair_id = keypair.name
break
if existing_keypair_id:
# 删除已存在的密钥对
delete_keypair_request = NovaDeleteKeypairRequest(keypair_name=existing_keypair_id)
client.nova_delete_keypair(delete_keypair_request)
print(f"已删除名为 {keypair_name} 的密钥对")
# 创建新的密钥对
request_body = NovaCreateKeypairRequestBody(
nova_keypair=NovaKeyPairBody(name=keypair_name)
)
create_keypair_request = NovaCreateKeypairRequest()
create_keypair_request.body = request_body
create_keypair_response = client.nova_create_keypair(create_keypair_request)
print("创建密钥对成功:")
print(create_keypair_response)
# 获取密钥对信息
show_keypair_request = NovaShowKeypairRequest(keypair_name=keypair_name)
show_keypair_response = client.nova_show_keypair(show_keypair_request)
print("密钥对详细信息:")
print(show_keypair_response)
# 输出密钥对的详细信息
keypair_info = show_keypair_response.keypair
print(f"密钥对名称:{keypair_info.name}")
print(f"公钥指纹:{keypair_info.fingerprint}")
print(f"公钥:{keypair_info.public_key}")
except exceptions.ClientRequestException as e:
print("请求失败:")
print(f"状态码:{e.status_code}")
print(f"请求ID:{e.request_id}")
print(f"错误代码:{e.error_code}")
print(f"错误信息:{e.error_msg}")
弹性伸缩配置
在云服务器的/root/huawei 目录下编写 create_as_config.py 文件,并导入提供的 huaweicloudapi.py 文件获取连接。编写 Python 代码,调用 auto_scaling 类,创建华为云的弹性伸缩配置,具体要求为
(1) 伸缩配置名称:chinaskills_as_config;
(2) 镜像配置:CentOS 7.5 64bit;
(3) 磁盘配置:系统盘规格 SSD、大小 100G;数据盘规格 SSD、大小 50G;
(4) 规格配置:c6.large.2;
(5) 安全组配置:chinaskills_security_group;
(6) 秘钥对配置:chinaskills_keypair;
(7) 弹性公网配置:类型为全动态 BGP、带宽为 5 Mbit/s;
(8) 如果弹性伸缩配置已经存在,代码中需要先删除;
(9)使用其源码的 get 方法输出此弹性伸缩配置的详细信息。
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkas.v1.region.as_region import AsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkas.v1 import (
ListScalingConfigsRequest,
DeleteScalingConfigRequest,
CreateScalingConfigRequest,
CreateScalingConfigOption,
ScalingConfigMetadata,
ScalingConfigBlockDevice,
ScalingConfigNetworks,
ScalingConfigPersonality,
ScalingConfigRootVolume,
ScalingConfigDataVolumes,
ScalingConfigPublicip,
ScalingConfigEip,
ScalingConfigBandwidth,
ScalingConfig
)
if __name__ == "__main__":
# 从环境变量获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
print("错误:请设置环境变量 CLOUD_SDK_AK 和 CLOUD_SDK_SK!")
exit(1)
credentials = BasicCredentials(ak, sk)
client = AsClient.new_builder() \
.with_credentials(credentials) \
.with_region(AsRegion.value_of("cn-north-4")) \
.build()
try:
scaling_config_name = "chinaskills_as_config" # 替换为你的伸缩配置名称
# 镜像 ID、网络 ID、安全组 ID、密钥对名称等需要替换为实际的 ID 或名称
image_id = "your_image_id_here" # 替换为 CentOS 7.5 64bit 的镜像 ID
flavor = "c6.large.2" # 替换为 c6.large.2 规格
security_group_id = "your_security_group_id_here" # 替换为 chinaskills_security_group 的 ID
key_name = "chinaskills_keypair" # 密钥对名称
system_volume_size = 100 # 系统盘大小
data_volume_size = 50 # 数据盘大小
bandwidth_size = 5 # 弹性公网 IP 带宽大小
# 检查伸缩配置是否存在
list_configs_request = ListScalingConfigsRequest()
list_configs_response = client.list_scaling_configs(list_configs_request)
existing_config_id = None
for config in list_configs_response.scaling_configs:
if config.name == scaling_config_name:
existing_config_id = config.id
break
if existing_config_id:
# 删除已存在的伸缩配置
delete_config_request = DeleteScalingConfigRequest(scaling_config_id=existing_config_id)
client.delete_scaling_config(delete_config_request)
print(f"已删除名为 {scaling_config_name} 的伸缩配置")
# 创建新的伸缩配置
scaling_config_option = CreateScalingConfigOption(
name=scaling_config_name,
image_ref=image_id,
flavor=flavor,
security_groups=[security_group_id],
key_name=key_name,
metadata={"user_data": ""},
root_volume=ScalingConfigBlockDevice(
volume_type="SSD",
volume_size=system_volume_size,
delete_on_termination=True
),
data_volumes=[
ScalingConfigBlockDevice(
volume_type="SSD",
volume_size=data_volume_size,
delete_on_termination=True
)
],
publicip=ScalingConfigPublicip(
eip=ScalingConfigEip(
bandwidth=ScalingConfigBandwidth(
size=bandwidth_size,
share_type="PER",
charge_mode="traffic"
)
)
)
)
create_scaling_config_request = CreateScalingConfigRequest()
create_scaling_config_request.body = scaling_config_option
create_scaling_config_response = client.create_scaling_config(create_scaling_config_request)
created_config_id = create_scaling_config_response.id
print("创建伸缩配置成功:")
print(create_scaling_config_response)
# 获取伸缩配置信息
show_config_request = ListScalingConfigsRequest(scaling_config_name=scaling_config_name)
show_config_response = client.list_scaling_configs(show_config_request)
print("伸缩配置详细信息:")
print(show_config_response)
# 输出伸缩配置的详细信息
scaling_config_info = show_config_response.scaling_configs[0]
print(f"伸缩配置名称:{scaling_config_info.name}")
print(f"镜像 ID:{scaling_config_info.image_ref}")
print(f"规格:{scaling_config_info.flavor}")
print(f"安全组 ID:{scaling_config_info.security_groups[0]}")
print(f"系统盘大小:{scaling_config_info.root_volume.volume_size} GB")
print(f"数据盘大小:{scaling_config_info.data_volumes[0].volume_size} GB")
print(f"弹性公网 IP 带宽大小:{scaling_config_info.publicip.eip.bandwidth.size} Mbit/s")
except exceptions.ClientRequestException as e:
print("请求失败:")
print(f"状态码:{e.status_code}")
print(f"请求ID:{e.request_id}")
print(f"错误代码:{e.error_code}")
print(f"错误信息:{e.error_msg}")
- 点赞
- 收藏
- 关注作者
评论(0)