更新安全组 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

HelloAmazon.NET 社区!请分享您的经验,帮助我们改进Amazon SDK for .NET及其学习资源进行调查。此项调查大约需要 10 分钟能完成。

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

更新安全组

此示例向您演示如何使用Amazon SDK for .NET以向安全组添加规则。特别是,该示例添加了一个规则,以允许给定 TCP 端口上的入站流量,例如,该规则可用于到 EC2 实例的远程连接。应用程序采用现有安全组的 ID、CIDR 格式的 IP 地址(或地址范围)以及可选的 TCP 端口号。然后,它将入站规则添加到给定的安全组。

注意

要使用此示例,您需要一个 CIDR 格式的 IP 地址(或地址范围)。请参阅其他注意事项,以了解如何获取本地计算机 IP 地址的方法。

以下几节提供了代码段。这些区域有:示例的完整代码之后显示,并且可以按原样构建和运行。

添加入站规则

以下代码段为特定 IP 地址(或范围)和 TCP 端口添加入站规则到安全组。

示例本主题末尾显示了这个正在使用的代码片段。

// // Method that adds a TCP ingress rule to a security group private static async Task AddIngressRule( IAmazonEC2 eC2Client, string groupID, string ipAddress, int port) { // Create an object to hold the request information for the rule. // It uses an IpPermission object to hold the IP information for the rule. var ingressRequest = new AuthorizeSecurityGroupIngressRequest{ GroupId = groupID}; ingressRequest.IpPermissions.Add(new IpPermission{ IpProtocol = "tcp", FromPort = port, ToPort = port, Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } } }); // Create the inbound rule for the security group AuthorizeSecurityGroupIngressResponse responseIngress = await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest); Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}."); Console.WriteLine($"Result: {responseIngress.HttpStatusCode}"); }

代码完成

本节显示了此示例的相关参考和完整代码。

using System; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.EC2; using Amazon.EC2.Model; namespace EC2AddRuleForRDP { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to add a rule that allows inbound traffic on TCP a port class Program { private const int DefaultPort = 3389; static async Task Main(string[] args) { // Parse the command line and show help if necessary var parsedArgs = CommandLine.Parse(args); if(parsedArgs.Count == 0) { PrintHelp(); return; } // Get the application parameters from the parsed arguments var groupID = CommandLine.GetParameter(parsedArgs, null, "-g", "--group-id"); var ipAddress = CommandLine.GetParameter(parsedArgs, null, "-i", "--ip-address"); var portStr = CommandLine.GetParameter(parsedArgs, DefaultPort.ToString(), "-p", "--port"); if(string.IsNullOrEmpty(ipAddress)) CommandLine.ErrorExit("\nYou must supply an IP address in CIDR format."); if(string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-")) CommandLine.ErrorExit("\nThe ID for a security group is missing or incorrect."); if(int.Parse(portStr) == 0) CommandLine.ErrorExit($"\nThe given TCP port number, {portStr}, isn't allowed."); // Add a rule to the given security group that allows // inbound traffic on a TCP port await AddIngressRule( new AmazonEC2Client(), groupID, ipAddress, int.Parse(portStr)); } // // Method that adds a TCP ingress rule to a security group private static async Task AddIngressRule( IAmazonEC2 eC2Client, string groupID, string ipAddress, int port) { // Create an object to hold the request information for the rule. // It uses an IpPermission object to hold the IP information for the rule. var ingressRequest = new AuthorizeSecurityGroupIngressRequest{ GroupId = groupID}; ingressRequest.IpPermissions.Add(new IpPermission{ IpProtocol = "tcp", FromPort = port, ToPort = port, Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } } }); // Create the inbound rule for the security group AuthorizeSecurityGroupIngressResponse responseIngress = await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest); Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}."); Console.WriteLine($"Result: {responseIngress.HttpStatusCode}"); } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: EC2AddRuleForRDP -g <group-id> -i <ip-address> [-p <port>]" + "\n -g, --group-id: The ID of the security group to which you want to add the inbound rule." + "\n -i, --ip-address: An IP address or address range in CIDR format." + "\n -p, --port: The TCP port number. Defaults to 3389."); } } // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class that represents a command line on the console or terminal. // (This is the same for all examples. When you have seen it once, you can ignore it.) static class CommandLine { // Method to parse a command line of the form: "--param value" or "-p value". // If "param" is found without a matching "value", Dictionary.Value is an empty string. // If "value" is found without a matching "param", Dictionary.Key is "--NoKeyN" // where "N" represents sequential numbers. public static Dictionary<string,string> Parse(string[] args) { var parsedArgs = new Dictionary<string,string>(); int i = 0, n = 0; while(i < args.Length) { // If the first argument in this iteration starts with a dash it's an option. if(args[i].StartsWith("-")) { var key = args[i++]; var value = string.Empty; // Is there a value that goes with this option? if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++]; parsedArgs.Add(key, value); } // If the first argument in this iteration doesn't start with a dash, it's a value else { parsedArgs.Add("--NoKey" + n.ToString(), args[i++]); n++; } } return parsedArgs; } // // Method to get a parameter from the parsed command-line arguments public static string GetParameter( Dictionary<string,string> parsedArgs, string def, params string[] keys) { string retval = null; foreach(var key in keys) if(parsedArgs.TryGetValue(key, out retval)) break; return retval ?? def; } // // Exit with an error. public static void ErrorExit(string msg, int code=1) { Console.WriteLine("\nError"); Console.WriteLine(msg); Environment.Exit(code); } } }

其他注意事项

  • 如果不提供端口号,则应用程序默认为端口 3389。这是 Windows RDP 的端口,使您能够连接到运行 Windows 的 EC2 实例。如果您要启动运行 Linux 的 EC2 实例,则可以改为使用 TCP 端口 22 (SSH)。

  • 请注意,该示例设置IpProtocol更改为 “tcp”。值IpProtocol可以在描述中找到IpProtocol属性IpPermission类。

  • 当您使用此示例时,您可能需要本地计算机的 IP 地址。以下是您可以通过以下几种方法来获取地址。

    • 如果您的本地计算机(您将从中连接到 EC2 实例)具有静态公有 IP 地址,则可以使用服务获取该地址。其中一项服务是http://checkip.amazonaws.com/。有关授权入站流量的更多信息,请参阅Linux 的 EC2 用户指南适用于 Windows 的 EC2 用户指南

    • 获取本地计算机 IP 地址的另一种方法是使用Amazon EC2 控制台

      选择其中一个安全组,选择入站规则选项卡,然后选择编辑入站规则。在入站规则中,打开列,然后选择我的 IP以查看 CIDR 格式的本地计算机的 IP 地址。请务必Cancel操作。