以编程方式管理Windows防火墙
本文关键字:Windows 防火墙 管理 方式 编程 | 更新日期: 2023-09-27 18:25:54
我正在尝试以编程方式创建出站Windows防火墙规则。此外,我想以编程方式启用和禁用此规则。我该如何在C#中执行此操作?手动操作,我可以进入控制面板,单击Windows防火墙,然后单击高级设置。
最好使用Windows库C:''Windows''system32''FirewallAPI.dll。此dll从Windows 7开始提供。如果将此COM库添加到项目引用中,Visual Studio将自动为其添加包装,或者可以使用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应该为您提供有关库的足够详细信息。
您可以使用此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);
您可以将netsh advfirewall命令语法封装到一个小库中,以便根据需要启用/禁用设置。如果失败,请参阅http://msdn.microsoft.com/en-us/library/windows/desktop/ff956124(v=vs.85).aspx,适用于具有高级安全性的Windows防火墙API。
您可以使用;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();
}
}