最近项目中需要通过程序自动设置windows 防火墙,查了一下资料,可以通过命令行netsh firewall来实现。封装了一个类来实现对允许放开的程序(Allowed program)进行管理。管理其他内容比如放开端口等方法是类似的。
通过编程管理windows 防火墙
作者:肖波
最近项目中需要通过程序自动设置windows 防火墙,查了一下资料,可以通过命令行netsh firewall来实现。封装了一个类来实现对允许放开的程序(Allowed program)进行管理。管理其他内容比如放开端口等方法是类似的。
程序中用到一个公共类 RunProcess,这个类可从我的另一篇文章
一个C#写的调用外部进程类 获得
namespace WinFirewall


{

public enum TScope

{
ALL,
SUBNET,
CUSTOM,
}

public enum TMode

{
ENABLE,
DISABLE,
}


/**//// <summary>
/// Manage the allowed program with the Windows Firewall.
/// </summary>
public class AllowedProgram

{

Set AllowedProgram Help#region Set AllowedProgram Help

/**//*
set allowedprogram

[ program = ] path
[ [ name = ] name
[ mode = ] ENABLE|DISABLE
[ scope = ] ALL|SUBNET|CUSTOM
[ addresses = ] addresses
[ profile = ] CURRENT|DOMAIN|STANDARD|ALL ]

Sets firewall allowed program configuration.

Parameters:

program - Program path and file name.

name - Program name (optional).

mode - Program mode (optional).
ENABLE - Allow through firewall (default).
DISABLE - Do not allow through firewall.

scope - Program scope (optional).
ALL - Allow all traffic through firewall (default).
SUBNET - Allow only local network (subnet) traffic through firewall.
CUSTOM - Allow only specified traffic through firewall.

addresses - Custom scope addresses (optional).

profile - Configuration profile (optional).
CURRENT - Current profile (default).
DOMAIN - Domain profile.
STANDARD - Standard profile.
ALL - All profiles.

Remarks: 'scope' must be 'CUSTOM' to specify 'addresses'.

Examples:

set allowedprogram C:\MyApp\MyApp.exe MyApp ENABLE

set allowedprogram C:\MyApp\MyApp.exe MyApp DISABLE

set allowedprogram C:\MyApp\MyApp.exe MyApp ENABLE CUSTOM

157.60.0.1,172.16.0.0/16,10.0.0.0/255.0.0.0,LocalSubnet
set allowedprogram program = C:\MyApp\MyApp.exe name = MyApp mode = ENABLE

set allowedprogram program = C:\MyApp\MyApp.exe name = MyApp mode = DISABLE
set allowedprogram program = C:\MyApp\MyApp.exe name = MyApp mode = ENABLE

scope = CUSTOM addresses =
157.60.0.1,172.16.0.0/16,10.0.0.0/255.0.0.0,LocalSubnet
*/
#endregion


private field#region private field
private String m_Program;
private String m_Name;
private TScope m_Scope = TScope.ALL;
private TMode m_Mode = TMode.ENABLE;
private String m_Address;
#endregion


public property#region public property

/**//// <summary>
/// Program path and file name.
/// </summary>
public String Program

{
get

{
return m_Program;
}

set

{
m_Program = value;
}
}


/**//// <summary>
/// Program name (optional).
/// </summary>
public String Name

{
get

{
return m_Name;
}

set

{
m_Name = value;
}
}


/**//// <summary>
/// Program scope (optional).
/// ALL - Allow all traffic through firewall (default).
/// SUBNET - Allow only local network (subnet) traffic through firewall.
/// CUSTOM - Allow only specified traffic through firewall. /// </summary>
public TScope Scope

{
get

{
return m_Scope;
}

set

{
m_Scope = value;
}
}


/**//// <summary>
/// Program mode (optional).
/// ENABLE - Allow through firewall (default).
/// DISABLE - Do not allow through firewall
/// </summary>
public TMode Mode

{
get

{
return m_Mode;
}

set

{
m_Mode = value;
}
}


/**//// <summary>
/// Custom scope addresses (optional).
/// </summary>
/// <example>
/// 157.60.0.1,172.16.0.0/16,10.0.0.0/255.0.0.0
/// </example>
public String Address

{
get

{
return m_Address;
}

set

{
m_Address = value;
}
}

#endregion


public method#region public method

/**//// <summary>
/// Set allowed program
/// </summary>
public void Set()

{
Debug.Assert(Program != null);

if (Name == null)

{
Name = System.IO.Path.GetFileNameWithoutExtension(Program);
}

if (Scope == TScope.CUSTOM)

{
Debug.Assert(Address != null);
}

RunProcess runCmd = new RunProcess();
String command;

command = String.Format("firewall set allowedprogram {0} {1} {2} {3}",
Program, Name, Mode.ToString(), Scope.ToString());

if (Scope == TScope.CUSTOM)

{
command += " " + Address;
}

runCmd.Run("netsh", command);

if (runCmd.Error != null && runCmd.Error != "")

{
throw new Exception(runCmd.Error);
}

if (!runCmd.Output.ToLower().Contains("ok."))

{
throw new Exception(runCmd.Output);
}
}


/**//// <summary>
/// Delete allowed program
/// </summary>
public void Delete()

{
Debug.Assert(Program != null);

RunProcess runCmd = new RunProcess();

String command = String.Format("firewall delete allowedprogram {0}",
Program);

runCmd.Run("netsh", command);

if (runCmd.Error != null && runCmd.Error != "")

{
throw new Exception(runCmd.Error);
}

if (!runCmd.Output.ToLower().Contains("ok."))

{
throw new Exception(runCmd.Output);
}
}

#endregion
}
}

调用的相关例程
private void buttonSetAllowProgram_Click(object sender, EventArgs e)

{
try

{
AllowedProgram allowedProgram = new AllowedProgram();
allowedProgram.Program = textBoxProgramFilePath.Text.Trim();

if (checkBoxEnable.Checked)

{
allowedProgram.Mode = TMode.ENABLE;
}
else

{
allowedProgram.Mode = TMode.DISABLE;
}

allowedProgram.Scope = (TScope)comboBoxScope.SelectedItem;

allowedProgram.Address = textBoxAddress.Text.Trim();

allowedProgram.Set();

MessageBox.Show("OK", "Information", MessageBoxButtons.OK);
}
catch (Exception e1)

{
MessageBox.Show(e1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void buttonDelAllowProgram_Click(object sender, EventArgs e)

{
try

{
AllowedProgram allowedProgram = new AllowedProgram();
allowedProgram.Program = textBoxProgramFilePath.Text.Trim();
allowedProgram.Delete();

MessageBox.Show("OK", "Information", MessageBoxButtons.OK);
}
catch (Exception e1)

{
MessageBox.Show(e1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述