使用 AWS SDK 为 Amazon EC2 安全组设置入站规则
以下代码示例显示如何为 Amazon EC2 安全组设置入站规则。
操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:
- .NET
-
- AWS SDK for .NET
-
注意
在 GitHub 上查看更多内容。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 /// <summary> /// Authorize the local computer ingress to EC2 instances associated /// with the virtual private cloud (VPC) security group. /// </summary> /// <param name="groupName">The name of the security group.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> AuthorizeSecurityGroupIngress(string groupName) { // Get the IP address for the local computer. var ipAddress = await GetIpAddress(); Console.WriteLine($"Your IP address is: {ipAddress}"); var ipRanges = new List<IpRange> { new IpRange { CidrIp = $"{ipAddress}/32" } }; var permission = new IpPermission { Ipv4Ranges = ipRanges, IpProtocol = "tcp", FromPort = 22, ToPort = 22 }; var permissions = new List<IpPermission> { permission }; var response = await _amazonEC2.AuthorizeSecurityGroupIngressAsync( new AuthorizeSecurityGroupIngressRequest(groupName, permissions)); return response.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Authorize the local computer for ingress to /// the Amazon EC2 SecurityGroup. /// </summary> /// <returns>The IPv4 address of the computer running the scenario.</returns> private static async Task<string> GetIpAddress() { var httpClient = new HttpClient(); var ipString = await httpClient.GetStringAsync("https://checkip.amazonaws.com"); // The IP address is returned with a new line // character on the end. Trim off the whitespace and // return the value to the caller. return ipString.Trim(); }
-
有关 API 详细信息,请参阅《AWS SDK for .NET API 参考》中的 AuthorizeSecurityGroupIngress。
-
- C++
-
- 适用于 C++ 的 SDK
-
注意
在 GitHub 上查看更多内容。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::IpRange ip_range; ip_range.SetCidrIp("0.0.0.0/0"); Aws::EC2::Model::IpPermission permission1; permission1.SetIpProtocol("tcp"); permission1.SetToPort(80); permission1.SetFromPort(80); permission1.AddIpRanges(ip_range); authorize_request.AddIpPermissions(permission1); Aws::EC2::Model::IpPermission permission2; permission2.SetIpProtocol("tcp"); permission2.SetToPort(22); permission2.SetFromPort(22); permission2.AddIpRanges(ip_range); authorize_request.AddIpPermissions(permission2); const Aws::EC2::Model::AuthorizeSecurityGroupIngressOutcome authorizeOutcome = ec2Client.AuthorizeSecurityGroupIngress(authorizeRequest); if (!authorizeOutcome.IsSuccess()) { std::cerr << "Failed to set ingress policy for security group " << groupName << ":" << authorizeOutcome.GetError().GetMessage() << std::endl; return false; } std::cout << "Successfully added ingress policy to security group " << groupName << std::endl;
-
有关 API 详细信息,请参阅《AWS SDK for C++ API 参考》中的 AuthorizeSecurityGroupIngress。
-
- Java
-
- SDK for Java 2.x
-
注意
在 GitHub 上查看更多内容。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 public static String createSecurityGroup(Ec2Client ec2,String groupName, String groupDesc, String vpcId, String myIpAddress) { try { CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder() .groupName(groupName) .description(groupDesc) .vpcId(vpcId) .build(); CreateSecurityGroupResponse resp= ec2.createSecurityGroup(createRequest); IpRange ipRange = IpRange.builder() .cidrIp(myIpAddress+"/0") .build(); IpPermission ipPerm = IpPermission.builder() .ipProtocol("tcp") .toPort(80) .fromPort(80) .ipRanges(ipRange) .build(); IpPermission ipPerm2 = IpPermission.builder() .ipProtocol("tcp") .toPort(22) .fromPort(22) .ipRanges(ipRange) .build(); AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest.builder() .groupName(groupName) .ipPermissions(ipPerm, ipPerm2) .build(); ec2.authorizeSecurityGroupIngress(authRequest); System.out.println("Successfully added ingress policy to security group "+groupName); return resp.groupId(); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
-
有关 API 详细信息,请参阅《AWS SDK for Java 2.x API 参考》中的 AuthorizeSecurityGroupIngress。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
在 GitHub 上查看更多内容。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 import { AuthorizeSecurityGroupIngressCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; // Grant permissions for a single IP address to ssh into instances // within the provided security group. export const main = async () => { const command = new AuthorizeSecurityGroupIngressCommand({ // Replace with a security group ID from the AWS console or // the DescribeSecurityGroupsCommand. GroupId: "SECURITY_GROUP_ID", IpPermissions: [ { IpProtocol: "tcp", FromPort: 22, ToPort: 22, // Replace 0.0.0.0 with the IP address to authorize. // For more information on this notation, see // https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation IpRanges: [{ CidrIp: "0.0.0.0/32" }], }, ], }); try { const { SecurityGroupRules } = await client.send(command); console.log(JSON.stringify(SecurityGroupRules, null, 2)); } catch (err) { console.error(err); } };
-
有关 API 详细信息,请参阅《AWS SDK for JavaScript API 参考》中的 AuthorizeSecurityGroupIngress。
-
- Kotlin
-
- SDK for Kotlin
-
注意
这是适用于预览版中特征的预发行文档。本文档随时可能更改。
注意
在 GitHub 上查看更多内容。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 suspend fun createEC2SecurityGroupSc(groupNameVal: String?, groupDescVal: String?, vpcIdVal: String?, myIpAddress: String?): String? { val request = CreateSecurityGroupRequest { groupName = groupNameVal description = groupDescVal vpcId = vpcIdVal } Ec2Client { region = "us-west-2" }.use { ec2 -> val resp = ec2.createSecurityGroup(request) val ipRange = IpRange { cidrIp = "$myIpAddress/0" } val ipPerm = IpPermission { ipProtocol = "tcp" toPort = 80 fromPort = 80 ipRanges = listOf(ipRange) } val ipPerm2 = IpPermission { ipProtocol = "tcp" toPort = 22 fromPort = 22 ipRanges = listOf(ipRange) } val authRequest = AuthorizeSecurityGroupIngressRequest { groupName = groupNameVal ipPermissions = listOf(ipPerm, ipPerm2) } ec2.authorizeSecurityGroupIngress(authRequest) println("Successfully added ingress policy to Security Group $groupNameVal") return resp.groupId } }
-
有关 API 详细信息,请参阅《AWS SDK for Kotlin API 参考》中的 AuthorizeSecurityGroupIngress
。
-
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
注意
在 GitHub 上查看更多内容。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 class SecurityGroupWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions.""" def __init__(self, ec2_resource, security_group=None): """ :param ec2_resource: A Boto3 Amazon EC2 resource. This high-level resource is used to create additional high-level objects that wrap low-level Amazon EC2 service actions. :param security_group: A Boto3 SecurityGroup object. This is a high-level object that wraps security group actions. """ self.ec2_resource = ec2_resource self.security_group = security_group @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource) def authorize_ingress(self, ssh_ingress_ip): """ Adds a rule to the security group to allow access to SSH. :param ssh_ingress_ip: The IP address that is granted inbound access to connect to port 22 over TCP, used for SSH. :return: The response to the authorization request. The 'Return' field of the response indicates whether the request succeeded or failed. """ if self.security_group is None: logger.info("No security group to update.") return try: ip_permissions = [ { # SSH ingress open to only the specified IP address. "IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "IpRanges": [{"CidrIp": f"{ssh_ingress_ip}/32"}], } ] response = self.security_group.authorize_ingress( IpPermissions=ip_permissions ) except ClientError as err: logger.error( "Couldn't authorize inbound rules for %s. Here's why: %s: %s", self.security_group.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response
-
有关 API 详细信息,请参阅《AWS SDK for Python(Boto3)API 参考》中的 AuthorizeSecurityGroupIngress。
-
有关 AWS 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 Amazon EC2 与 AWS SDK 结合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。