更新安全群組 - AWS SDK for .NET

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

更新安全群組

此範例示範如何使用 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 套件:

程式設計元素:

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 地址。以下是您可以取得地址的一些方式。

  • 您可以在 Amazon EC2主控台 中檢查安全群組清單,以驗證此範例的結果。