与 AWS SDK或DescribeSecurityGroups一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或DescribeSecurityGroups一起使用 CLI

以下代码示例演示如何使用 DescribeSecurityGroups

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/// <summary> /// Retrieve information for one or all Amazon EC2 security group. /// </summary> /// <param name="groupId">The optional Id of a specific Amazon EC2 security group.</param> /// <returns>A list of security group information.</returns> public async Task<List<SecurityGroup>> DescribeSecurityGroups(string groupId) { try { var securityGroups = new List<SecurityGroup>(); var request = new DescribeSecurityGroupsRequest(); if (!string.IsNullOrEmpty(groupId)) { var groupIds = new List<string> { groupId }; request.GroupIds = groupIds; } var paginatorForSecurityGroups = _amazonEC2.Paginators.DescribeSecurityGroups(request); await foreach (var securityGroup in paginatorForSecurityGroups.SecurityGroups) { securityGroups.Add(securityGroup); } return securityGroups; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidGroup.NotFound") { _logger.LogError( $"A security group {groupId} does not exist."); } throw; } catch (Exception ex) { _logger.LogError( $"An error occurred while listing security groups. {ex.Message}"); throw; } } /// <summary> /// Display the information returned by the call to /// DescribeSecurityGroupsAsync. /// </summary> /// <param name="securityGroup">A list of security group information.</param> public void DisplaySecurityGroupInfoAsync(SecurityGroup securityGroup) { Console.WriteLine($"{securityGroup.GroupName}"); Console.WriteLine("Ingress permissions:"); securityGroup.IpPermissions.ForEach(permission => { Console.WriteLine($"\tFromPort: {permission.FromPort}"); Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}"); Console.Write($"\tIpv4Ranges: "); permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); }); Console.WriteLine($"\n\tIpv6Ranges:"); permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); }); Console.Write($"\n\tPrefixListIds: "); permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} ")); Console.WriteLine($"\n\tTo Port: {permission.ToPort}"); }); Console.WriteLine("Egress permissions:"); securityGroup.IpPermissionsEgress.ForEach(permission => { Console.WriteLine($"\tFromPort: {permission.FromPort}"); Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}"); Console.Write($"\tIpv4Ranges: "); permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); }); Console.WriteLine($"\n\tIpv6Ranges:"); permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); }); Console.Write($"\n\tPrefixListIds: "); permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} ")); Console.WriteLine($"\n\tTo Port: {permission.ToPort}"); }); }
Bash
AWS CLI 使用 Bash 脚本
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

############################################################################### # function ec2_describe_security_groups # # This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups. # # Parameters: # -g security_group_id - The ID of the security group to describe (optional). # # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_describe_security_groups() { local security_group_id response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_describe_security_groups" echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups." echo " -g security_group_id - The ID of the security group to describe (optional)." echo "" } # Retrieve the calling parameters. while getopts "g:h" option; do case "${option}" in g) security_group_id="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 local query="SecurityGroups[*].[GroupName, GroupId, VpcId, IpPermissions[*].[IpProtocol, FromPort, ToPort, IpRanges[*].CidrIp]]" if [[ -n "$security_group_id" ]]; then response=$(aws ec2 describe-security-groups --group-ids "$security_group_id" --query "${query}" --output text) else response=$(aws ec2 describe-security-groups --query "${query}" --output text) fi local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports describe-security-groups operation failed.$response" return 1 fi echo "$response" return 0 }

本示例中使用的实用程序函数。

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) security groups, or a specific group. /*! \param groupID: A group ID, ignored if empty. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::describeSecurityGroups(const Aws::String &groupID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::DescribeSecurityGroupsRequest request; if (!groupID.empty()) { request.AddGroupIds(groupID); } Aws::String nextToken; do { if (!nextToken.empty()) { request.SetNextToken(nextToken); } Aws::EC2::Model::DescribeSecurityGroupsOutcome outcome = ec2Client.DescribeSecurityGroups(request); if (outcome.IsSuccess()) { std::cout << std::left << std::setw(32) << "Name" << std::setw(30) << "GroupId" << std::setw(30) << "VpcId" << std::setw(64) << "Description" << std::endl; const std::vector<Aws::EC2::Model::SecurityGroup> &securityGroups = outcome.GetResult().GetSecurityGroups(); for (const auto &securityGroup: securityGroups) { std::cout << std::left << std::setw(32) << securityGroup.GetGroupName() << std::setw(30) << securityGroup.GetGroupId() << std::setw(30) << securityGroup.GetVpcId() << std::setw(64) << securityGroup.GetDescription() << std::endl; } } else { std::cerr << "Failed to describe security groups:" << outcome.GetError().GetMessage() << std::endl; return false; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); return true; }
CLI
AWS CLI

示例 1:描述安全组

以下 describe-security-groups 示例描述了指定的安全组。

aws ec2 describe-security-groups \ --group-ids sg-903004f8

输出:

{ "SecurityGroups": [ { "IpPermissionsEgress": [ { "IpProtocol": "-1", "IpRanges": [ { "CidrIp": "0.0.0.0/0" } ], "UserIdGroupPairs": [], "PrefixListIds": [] } ], "Description": "My security group", "Tags": [ { "Value": "SG1", "Key": "Name" } ], "IpPermissions": [ { "IpProtocol": "-1", "IpRanges": [], "UserIdGroupPairs": [ { "UserId": "123456789012", "GroupId": "sg-903004f8" } ], "PrefixListIds": [] }, { "PrefixListIds": [], "FromPort": 22, "IpRanges": [ { "Description": "Access from NY office", "CidrIp": "203.0.113.0/24" } ], "ToPort": 22, "IpProtocol": "tcp", "UserIdGroupPairs": [] } ], "GroupName": "MySecurityGroup", "VpcId": "vpc-1a2b3c4d", "OwnerId": "123456789012", "GroupId": "sg-903004f8", } ] }

示例 2:描述具有特定规则的安全组

以下describe-security-groups示例使用过滤器将结果范围限定为具有允许SSH流量的规则(端口 22)和允许来自所有地址的流量的规则(0.0.0.0/0)的安全组。示例使用 --query 参数仅显示安全组的名称。安全组必须匹配要在结果中返回的所有筛选条件;但是,单个规则不必匹配所有筛选条件。例如,输出返回一个安全组,其中一条规则允许来自特定 IP 地址的SSH流量,另一条规则允许来自所有地址的HTTP流量。

aws ec2 describe-security-groups \ --filters Name=ip-permission.from-port,Values=22 Name=ip-permission.to-port,Values=22 Name=ip-permission.cidr,Values='0.0.0.0/0' \ --query "SecurityGroups[*].[GroupName]" \ --output text

输出:

default my-security-group web-servers launch-wizard-1

示例 3:根据标签描述安全组

以下 describe-security-groups 示例使用筛选器,将结果范围限定为安全组名称中包含 test 且带有标签 Test=To-delete 的安全组。该示例使用--query参数仅显示安全组IDs的名称和名称。

aws ec2 describe-security-groups \ --filters Name=group-name,Values=*test* Name=tag:Test,Values=To-delete \ --query "SecurityGroups[*].{Name:GroupName,ID:GroupId}"

输出:

[ { "Name": "testfornewinstance", "ID": "sg-33bb22aa" }, { "Name": "newgrouptest", "ID": "sg-1a2b3c4d" } ]

有关使用标签筛选条件的其他示例,请参阅 Amazon EC2 用户指南中的使用标签

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/** * Asynchronously describes the security groups for the specified group ID. * * @param groupName the name of the security group to describe * @return a {@link CompletableFuture} that represents the asynchronous operation * of describing the security groups. The future will complete with a * {@link DescribeSecurityGroupsResponse} object that contains the * security group information. */ public CompletableFuture<String> describeSecurityGroupArnByNameAsync(String groupName) { DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder() .groupNames(groupName) .build(); DescribeSecurityGroupsPublisher paginator = getAsyncClient().describeSecurityGroupsPaginator(request); AtomicReference<String> groupIdRef = new AtomicReference<>(); return paginator.subscribe(response -> { response.securityGroups().stream() .filter(securityGroup -> securityGroup.groupName().equals(groupName)) .findFirst() .ifPresent(securityGroup -> groupIdRef.set(securityGroup.groupId())); }).thenApply(v -> { String groupId = groupIdRef.get(); if (groupId == null) { throw new RuntimeException("No security group found with the name: " + groupName); } return groupId; }).exceptionally(ex -> { logger.info("Failed to describe security group: " + ex.getMessage()); throw new RuntimeException("Failed to describe security group", ex); }); }
JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

import { DescribeSecurityGroupsCommand, EC2Client } from "@aws-sdk/client-ec2"; /** * Describes the specified security groups or all of your security groups. * @param {{ groupIds: string[] }} options */ export const main = async ({ groupIds = [] }) => { const client = new EC2Client({}); const command = new DescribeSecurityGroupsCommand({ GroupIds: groupIds, }); try { const { SecurityGroups } = await client.send(command); const sgList = SecurityGroups.map( (sg) => `• ${sg.GroupName} (${sg.GroupId}): ${sg.Description}`, ).join("\n"); if (sgList.length) { console.log(`Security groups:\n${sgList}`); } else { console.log("No security groups found."); } } catch (caught) { if (caught instanceof Error && caught.name === "InvalidGroupId.Malformed") { console.warn(`${caught.message}. Please provide a valid GroupId.`); } else if ( caught instanceof Error && caught.name === "InvalidGroup.NotFound" ) { console.warn(caught.message); } else { throw caught; } } };
Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

suspend fun describeEC2SecurityGroups(groupId: String) { val request = DescribeSecurityGroupsRequest { groupIds = listOf(groupId) } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.describeSecurityGroups(request) response.securityGroups?.forEach { group -> println("Found Security Group with id ${group.groupId}, vpc id ${group.vpcId} and description ${group.description}") } } }
PowerShell
用于 PowerShell

示例 1:此示例描述了为指定的安全组VPC。使用属于的安全组时,必须使用安全组 ID(-GroupId 参数),而不是名称(-GroupName 参数)来引用该组。VPC

Get-EC2SecurityGroup -GroupId sg-12345678

输出:

Description : default VPC security group GroupId : sg-12345678 GroupName : default IpPermissions : {Amazon.EC2.Model.IpPermission} IpPermissionsEgress : {Amazon.EC2.Model.IpPermission} OwnerId : 123456789012 Tags : {} VpcId : vpc-12345678

示例 2:此示例描述了 EC2-Classic 的指定安全组。在 EC2-Classic 中使用安全组时,您可以使用组名称(-GroupName 参数)或组 ID(-GroupId 参数)来引用安全组。

Get-EC2SecurityGroup -GroupName my-security-group

输出:

Description : my security group GroupId : sg-45678901 GroupName : my-security-group IpPermissions : {Amazon.EC2.Model.IpPermission, Amazon.EC2.Model.IpPermission} IpPermissionsEgress : {} OwnerId : 123456789012 Tags : {} VpcId :

示例 3:此示例检索 vpc-0fc1ff23456b789eb 的所有安全组

Get-EC2SecurityGroup -Filter @{Name="vpc-id";Values="vpc-0fc1ff23456b789eb"}
Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

class SecurityGroupWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions.""" def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None): """ Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID. :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level access to AWS EC2 services. :param security_group: The ID of a security group to manage. This is a high-level identifier that represents the security group. """ self.ec2_client = ec2_client self.security_group = security_group @classmethod def from_client(cls) -> "SecurityGroupWrapper": """ Creates a SecurityGroupWrapper instance with a default EC2 client. :return: An instance of SecurityGroupWrapper initialized with the default EC2 client. """ ec2_client = boto3.client("ec2") return cls(ec2_client) def describe(self, security_group_id: Optional[str] = None) -> bool: """ Displays information about the specified security group or all security groups if no ID is provided. :param security_group_id: The ID of the security group to describe. If None, an open search is performed to describe all security groups. :returns: True if the description is successful. :raises ClientError: If there is an error describing the security group(s), such as an invalid security group ID. """ try: paginator = self.ec2_client.get_paginator("describe_security_groups") if security_group_id is None: # If no ID is provided, return all security groups. page_iterator = paginator.paginate() else: page_iterator = paginator.paginate(GroupIds=[security_group_id]) for page in page_iterator: for security_group in page["SecurityGroups"]: print(f"Security group: {security_group['GroupName']}") print(f"\tID: {security_group['GroupId']}") print(f"\tVPC: {security_group['VpcId']}") if security_group["IpPermissions"]: print("Inbound permissions:") pp(security_group["IpPermissions"]) return True except ClientError as err: logger.error("Failed to describe security group(s).") if err.response["Error"]["Code"] == "InvalidGroup.NotFound": logger.error( f"Security group {security_group_id} does not exist " f"because the specified security group ID was not found." ) raise
Rust
SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

async fn show_security_groups(client: &aws_sdk_ec2::Client, group_ids: Vec<String>) { let response = client .describe_security_groups() .set_group_ids(Some(group_ids)) .send() .await; match response { Ok(output) => { for group in output.security_groups() { println!( "Found Security Group {} ({}), vpc id {} and description {}", group.group_name().unwrap_or("unknown"), group.group_id().unwrap_or("id-unknown"), group.vpc_id().unwrap_or("vpcid-unknown"), group.description().unwrap_or("(none)") ); } } Err(err) => { let err = err.into_service_error(); let meta = err.meta(); let message = meta.message().unwrap_or("unknown"); let code = meta.code().unwrap_or("unknown"); eprintln!("Error listing EC2 Security Groups: ({code}) {message}"); } } }
SAP ABAP
SDK对于 SAP ABAP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

TRY. DATA lt_group_ids TYPE /aws1/cl_ec2groupidstrlist_w=>tt_groupidstringlist. APPEND NEW /aws1/cl_ec2groupidstrlist_w( iv_value = iv_group_id ) TO lt_group_ids. oo_result = lo_ec2->describesecuritygroups( it_groupids = lt_group_ids ). " oo_result is returned for testing purposes. " DATA(lt_security_groups) = oo_result->get_securitygroups( ). MESSAGE 'Retrieved information about security groups.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.