以编程方式管理Windows FireWall

时间:2012-02-27 20:20:50

标签: c# windows-firewall

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

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

您可以使用此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);

答案 2 :(得分:0)

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

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应该为您提供有关lib的足够详细信息。

答案 3 :(得分:0)

您可以使用“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();
            }
        }