1、写一份json文件:将要添加防火墙例外的应用程序和端口写入到json文件中

2、打开防火墙,读取json文件添加例外

    /// <summary>
/// Firewall.xaml 的交互逻辑
/// </summary>
public partial class Firewall : Window
{
private string udpPort = "";
private string tcpPort = "";
public Firewall()
{
//this.Hide();
InitializeComponent();
string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FirewallPort.json");
if (File.Exists(filePath))
{
//打开防火墙
try
{
string setStr = System.IO.File.ReadAllText(filePath);//获取json 内容
JObject joset = (JObject)JsonConvert.DeserializeObject(setStr); if (!string.IsNullOrEmpty(joset["Udp"].ToString()) && !string.IsNullOrEmpty(joset["Tcp"].ToString()) && !string.IsNullOrEmpty(joset["ProcessName"].ToString()))
{
udpPort = joset["Udp"].ToString();
tcpPort = joset["Tcp"].ToString();
JArray proces = (JArray)joset["ProcessName"]; string vFWStatueStr = string.Empty;
vFWStatueStr = INetFireWallManger.FWIsOpen;
if (vFWStatueStr == "error")
{
RegistryKey rsg = null;
try
{
rsg = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile"); string vKeyValue = rsg.GetValue("EnableFirewall").ToString();
if (vKeyValue == "0")//0表示关闭 , 1表示打开
{
vFWStatueStr = "False";
}
else if (vKeyValue == "1")
{
vFWStatueStr = "True";
}
INetFireWallManger.OpenFireWall();
AddFirewall(vFWStatueStr, tcpPort, udpPort, proces);
}
catch (Exception)
{
vFWStatueStr = "error";
}
finally
{
rsg.Close();
}
}
else
{
AddFirewall(vFWStatueStr, tcpPort, udpPort, proces);
}
}
}
catch
{ }
}
} private void AddFirewall(string statusStr, string tcpPort, string udpPort, JArray process)
{
RegistryKey key;
string ServicerName= "MpsSvc";
key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\CurrentControlSet\\Services\\MpsSvc", true);
var StartIndex = key.GetValue("Start").ToString();
if (StartIndex == "4")
{
ProcessStartInfo objProInfo = new ProcessStartInfo();
objProInfo.FileName = "cmd.exe";
objProInfo.CreateNoWindow = false;
objProInfo.WindowStyle = ProcessWindowStyle.Hidden;
objProInfo.Arguments = "/c sc config " + ServicerName + " start= " + "auto";
Process.Start(objProInfo);
//挂起线程1s后启动服务
System.Threading.Thread.Sleep(1000);
} ServiceController serviceController1 = new ServiceController();
serviceController1.ServiceName = "MpsSvc";
serviceController1.MachineName = "."; if (serviceController1.Status != ServiceControllerStatus.Running)
{
serviceController1.Start();
} if (statusStr.ToLower() == "false")
{
INetFireWallManger.OpenFireWall();
}
string[] udpMess = udpPort.Split(',');
for (int u = 0; u < udpMess.Length; u++)
{
INetFireWallManger.NetFwAddPorts("Udp", Convert.ToInt32(udpMess[u]), "UDP");
}
string[] tdpMess = tcpPort.Split(',');
for (int t = 0; t < tdpMess.Length; t++)
{
INetFireWallManger.NetFwAddPorts("Tcp", Convert.ToInt32(tdpMess[t]), "TCP");
}
for (int i = 0; i < process.Count; i++)
{
System.Diagnostics.Process[] tProcess = System.Diagnostics.Process.GetProcessesByName(process[i]["process_name"].ToString());
if (tProcess.Count() != 0)
{
INetFireWallManger.NetFwAddApps(process[i]["process_name"].ToString(), tProcess[0].MainModule.FileName.ToString());
}
}
}
}

  3、具体的一下实现方法

public static void OpenFireWall()
{
string cmdStr = "netsh advfirewall set currentprofile state on";
//打开防火墙
List<string> upCmd = new List<string>();
upCmd.Add(("cd " + System.AppDomain.CurrentDomain.BaseDirectory));
upCmd.Add(cmdStr);
INetFireWallManger.Execute(upCmd);
} /// <summary>
/// 添加防火墙例外端口
/// </summary>
/// <param name="name">名称</param>
/// <param name="port">端口</param>
/// <param name="protocol">协议(TCP、UDP)</param>
public static void NetFwAddPorts(string name, int port, string protocol)
{
//创建firewall管理类的实例
INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); INetFwOpenPort objPort = (INetFwOpenPort)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwOpenPort")); objPort.Name = name;
objPort.Port = port;
if (protocol.ToUpper() == "TCP")
{
objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
}
else
{
objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
}
objPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
objPort.Enabled = true; bool exist = false;
//加入到防火墙的管理策略
foreach (INetFwOpenPort mPort in netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts)
{
if (objPort == mPort)
{
exist = true;
break;
}
}
if (!exist) netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(objPort);
}
/// <summary>
/// 防火墙是否打开
/// </summary>
static public string FWIsOpen
{
get
{
try
{
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
return mgr.LocalPolicy.CurrentProfile.FirewallEnabled.ToString();
}
catch (Exception)
{
return "error";
}
}
}
/// <summary>
/// 将应用程序添加到防火墙例外
/// </summary>
/// <param name="name">应用程序名称</param>
/// <param name="executablePath">应用程序可执行文件全路径</param>
public static void NetFwAddApps(string name, string executablePath)
{
//创建firewall管理类的实例
INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); INetFwAuthorizedApplication app = (INetFwAuthorizedApplication)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication")); //在例外列表里,程序显示的名称
app.Name = name; //程序的路径及文件名
app.ProcessImageFileName = executablePath;
//是否启用该规则
app.Enabled = true; //加入到防火墙的管理策略
netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app);
}

  欢迎评论,提出意见和建议,谢谢!

OpenFirewall的更多相关文章

  1. 使用PowerShell实现服务器常用软件的无人值守安装

    操作系统:windows server 2016 , windows server 2019 软件环境: 类型 名称 版本   系统功能 TelnetClien       IIS   启用Asp.n ...

随机推荐

  1. Cannot uninstall 'enum34'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

    更新tensorflow时遇到报错 Found existing installation: enum34 1.0.4Cannot uninstall 'enum34'. It is a distut ...

  2. JavaScript学习系列2一JavaScript中的变量作用域

    在写这篇文章之前,再次提醒一下 JavaScript 是大小写敏感的语言 // 'test', 'Test', 'TeSt' , 'TEST' 是4个不同的变量名 JavaScript中的变量,最重要 ...

  3. JAVA IO包的整理---------Exception

    EOFException Signals that an end of file or end of stream has been reached unexpectedly during input ...

  4. rest framework 节流

    一.简单节流示例 所谓节流就是控制用户访问频率,这里分为匿名用户(非登录用户)和登录用户的限制. 匿名用户:根据其 IP 限制其频率 登录用户:IP.用户名都 OK 获取用户请求 IP:request ...

  5. 如何使用ROS查找rgbdslam代码包框架的输入

    我想这是一个天大的错误,在没有对整个ROS下的代码有一个整体理性的认知时,我使用感性认知. 由于在跑他的测试代码时,只替换了两个节点的名称,相当于remap了它,以为就可以跑了,结果是不行的. 然后用 ...

  6. 清北刷题冲刺 11-02 p.m

    函数最值 #include<iostream> #include<cstdio> #include<cstring> #define maxn 100010 usi ...

  7. 明天找python工作,看看这几道Python面试题吧,Python面试题No14

    第1题: 如何解决验证码的问题,用什么模块,听过哪些人工打码平台? PIL.pytesser.tesseract模块 平台的话有:(打码平台特殊,不保证时效性) 云打码 挣码 斐斐打码 若快打码 超级 ...

  8. POJ3274-Gold Balanced Lineup

    题目链接:点击打开链接 Gold Balanced Lineup Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 16978 ...

  9. JMeter - 后处理器/脚本语言 - 比较

    当我们使用JMeter / Response数据处理进行密集负载测试时,我们可能会非常小心我们选择的后处理器/脚本语言的类型.在这篇文章中,我想说明这些后处理器/脚本语言如何影响测试的整体性能. 我们 ...

  10. Vue中的指令(听博主说总结的很好)

    指令[重点] 作用:简化Dom操作 参考:https://cn.vuejs.org/v2/api/#%E6%8C%87%E4%BB%A4 特点: 1.都是以v-开头 2.除了插值表达式,其它都写在标签 ...