本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
更新安全组
此示例向您展示如何使用 AWS 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}"); }
完整代码
本部分显示了本示例的相关参考和完整代码。
NuGet 包裹:
编程元素:
-
命名空间 Amazon。 EC2
Amazon 上课 EC2Client
-
命名空间 Amazon。 EC2.Model
班级 AuthorizeSecurityGroupIngressRequest
班级 AuthorizeSecurityGroupIngressResponse
班级 IpPermission
班级 IpRange
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 arguments from the parsed list var groupID = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id"); var ipAddress = CommandLine.GetArgument(parsedArgs, null, "-i", "--ip-address"); var portStr = CommandLine.GetArgument(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: "--key value" or "-k value". // // Parameters: // - args: The command-line arguments passed into the application by the system. // // Returns: // A Dictionary with string Keys and Values. // // If a key is found without a matching value, Dictionary.Value is set to the key // (including the dashes). // If a value is found without a matching key, Dictionary.Key is set to "--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 = key; // Check to see if there's 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 an argument from the parsed command-line arguments // // Parameters: // - parsedArgs: The Dictionary object returned from the Parse() method (shown above). // - defaultValue: The default string to return if the specified key isn't in parsedArgs. // - keys: An array of keys to look for in parsedArgs. public static string GetArgument( Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys) { string retval = null; foreach(var key in keys) if(parsedArgs.TryGetValue(key, out retval)) break; return retval ?? defaultReturn; } // // Method to exit the application 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
可以在IpPermission类IpProtocol
属性的描述中找到。
-
使用此示例时,您可能需要本地计算机的 IP 地址。以下是可以获取地址的一些方式。
-
如果您的本地计算机(您将从该计算机连接到您的EC2实例)具有静态公有 IP 地址,则可以使用服务来获取该地址。其中一项服务是 http://checkip.amazonaws.com/
。要了解有关授权入站流量的更多信息,请参阅 Amazon EC2 用户指南中的向安全组添加规则和针对不同用例的安全组规则。 -
获取本地计算机IP地址的另一种方法是使用 Amazon EC2 控制台
。 选择您的一个安全组,选择入站规则选项卡,然后选择编辑入站规则。在入站规则中,打开 “来源” 列中的下拉菜单,然后选择 “我的 IP” 以CIDR格式查看本地计算机的 IP 地址。请务必取消该操作。
-
-
您可以通过检查 Amazon EC2 控制台
中的安全组列表来验证此示例的结果。