10

我正在尝试以编程方式创建出站 Windows 防火墙规则。此外,我想以编程方式启用和禁用此规则。我该如何在 C# 中执行此操作?手动,我可以通过进入控制面板,单击 Windows 防火墙,然后单击高级设置来执行此操作。

4

4 回答 4

7

最好使用 Windows 库 C:\windows\system32\FirewallAPI.dll。此 DLL 从 Windows 7 开始可用。如果您将其添加到项目引用中,Visual Studio 将自动为该 COM 库添加一个包装器,或者您可以使用 tlbimp.exe 手动创建包装器。

using NetFwTypeLib;

INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Your rule description";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; // inbound
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.RemoteAddresses = "1.2.3.0/24"; // add more blocks comma separated
firewallRule.Name = "You rule name";
firewallPolicy.Rules.Add(firewallRule);

VS IntelliSense 应该为您提供有关该库的足够详细信息。

于 2018-08-28T15:12:25.193 回答
4

您可以将 netsh advfirewall 命令语法包装到一个小型库中,以允许您按需启用/禁用设置。否则,请参阅http://msdn.microsoft.com/en-us/library/windows/desktop/ff956124(v=vs.85).aspx了解具有高级安全 API 的 Windows 防火墙。

于 2012-02-27T20:24:51.033 回答
4

您可以使用这个 nuget 包WindowsFirewallHelper

PM> Install-Package WindowsFirewallHelper

示例代码为应用程序添加新的出站规则

var rule = FirewallManager.Instance.CreateApplicationRule(
    @"MyApp Rule",
    FirewallAction.Allow,
    @"C:\MyApp.exe"
);
rule.Direction = FirewallDirection.Outbound;
FirewallManager.Instance.Rules.Add(rule);
于 2020-09-23T11:17:05.733 回答
1

您可以使用“netsh”命令。制定一个方法来调用它。
如果您不想引用FirewallAPI.dll或安装 nuget ,请使用此选项WindowsFirewallHelper

例子:


        /// <summary>
        /// Creates a Firewall Rule on current computer. Uses 'netsh'
        /// </summary>
        /// <param name="rulename"></param>
        /// <param name="protocol"></param>
        /// <param name="port"></param>
        /// <param name="direction">"in" or "out"</param>
        /// <param name="action"></param>
        /// <returns>netsh command response</returns>
        public static string CreateFirewalPort(string rulename, string protocol, int port, string direction = "in", string action = "allow")
        {
            // https://support.microsoft.com/en-us/help/947709/how-to-use-the-netsh-advfirewall-firewall-context-instead-of-the-netsh

            //Remove any rule with the same name. Otherwise every time you run this code a new rule is added.  
            Process removeproc = new Process
            {
                StartInfo = {
                    FileName = "netsh",
                    Arguments = $@"advfirewall firewall delete rule name=""{rulename}""",
                    UseShellExecute = false,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true
                }
            };
            try
            {
                removeproc.Start();
                var output = removeproc.StandardOutput.ReadToEnd();
                removeproc.WaitForExit();
            }
            catch (Exception ex)
            {
                Log.Info(ex.Message);
            }

            Process process = new Process
            {
                StartInfo = {
                    FileName = "netsh",
                    Arguments = $@"advfirewall firewall add rule name=""{rulename}"" protocol={protocol} localport={port} dir={direction} action={action}",
                    UseShellExecute = false,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    RedirectStandardOutput = true
                }
            };

            try
            {
                process.Start();
                var output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                return output;
            }
            catch (Exception ex)
            {
                return ex.ExceptionToString();
            }
        }
于 2021-03-24T14:57:45.823 回答