他的回复:
import osfrom huaweicloudsdkcore.auth.credentials import BasicCredentialsfrom huaweicloudsdkvpc.v2.region.vpc_region import VpcRegionfrom huaweicloudsdkcore.exceptions import exceptionsfrom 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 delete_security_group(client, security_group_id): """ 删除指定的安全组 :param client: VPC客户端 :param security_group_id: 安全组ID """ request = DeleteSecurityGroupRequest(security_group_id=security_group_id) response = client.delete_security_group(request) print(f"Delete Security Group Response: {response}") def create_security_group(client, group_name): """ 创建一个新的安全组 :param client: VPC客户端 :param group_name: 安全组名称 :return: 新创建的安全组ID """ request = CreateSecurityGroupRequest() security_group_body = CreateSecurityGroupOption(name=group_name) request.body = CreateSecurityGroupRequestBody(security_group=security_group_body) response = client.create_security_group(request) print(f"Create Security Group Response: {response}") return response.security_group.id 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.security_group try: # 安全组名称 security_group_name = "chinaskills_security_group" # 获取安全组ID security_group_id = get_security_group_id_by_name(client, security_group_name) if security_group_id: print(f"Existing security group found with ID: {security_group_id}") # 删除现有的安全组 delete_security_group(client, security_group_id) # 创建新的安全组 new_security_group_id = create_security_group(client, security_group_name) print(f"New security group created with ID: {new_security_group_id}") # 输出新创建的安全组的详细信息 security_group_details = show_security_group(client, new_security_group_id) print(f"name={security_group_details.name} || security_group_rules={security_group_details.security_group_rules}") 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}")