DescribeSecurityGroups 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

DescribeSecurityGroups 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 DescribeSecurityGroups

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on 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 指令碼
注意

還有更多 on 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++
C++ 的 SDK
注意

還有更多 on 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
Java 2.x 的 SDK
注意

還有更多 on 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 for JavaScript (v3)
注意

還有更多 on 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 for Kotlin
注意

還有更多 on 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
for PowerShell 工具

範例 1:此範例說明 VPC 的指定安全群組。使用屬於 VPC 的安全群組時,您必須使用安全群組 ID (-GroupId 參數),而非名稱 (-GroupName 參數) 來參考群組。

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 for Python (Boto3)
注意

還有更多 on 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
  • 如需 API 詳細資訊,請參閱 DescribeSecurityGroups AWS SDK for Python (Boto3) Word 參考中的 API

Rust
Rust 的 SDK
注意

還有更多 on 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 for SAP ABAP
注意

還有更多 on 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.