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. npm设置代理提高下载速度

    *nix上给网络类程序设置代理的通用办法,即导出http_proxy/https_proxy环境变量对npm不起作用 需要用npm自己的配置命令来解决: npm set proxy $PROXY np ...

  2. Luogu 4868 Preprefix sum

    类似于树状数组维护区间的方法. 每一次询问要求$\sum_{i = 1}^{n}\sum_{j = 1}^{i}a_j$. 展开一下: $\sum_{i = 1}^{n}\sum_{j = 1}^{i ...

  3. Entity Framework Code-First(9.5):DataAnnotations - MaxLength Attribute

    DataAnnotations - MaxLength Attribute: MaxLength attribute can be applied to a string or array type ...

  4. linux c段错误分析方法

    from:http://blog.csdn.net/adaptiver/article/details/37656507 一. 段错误原因分析 1 使用非法的指针,包括使用未经初始化及已经释放的指针( ...

  5. JS使用replace替换字符串中的某段或某个字符

    函数的介绍参考:http://www.w3school.com.cn/jsref/jsref_replace.asp 下列代码将Hello World!中的World替换为Jim <html&g ...

  6. 更改数据,ExecuteNonQuery()

    using (mycon) { mycon.Open(); string MyTime; DateTime dtDate; MyTime = textBox1.Text.ToString(); str ...

  7. C# 写 LeetCode easy #20 Valid Parentheses

    20.Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...

  8. 历届试题_log大侠

    标题:Log大侠     atm参加了速算训练班,经过刻苦修炼,对以2为底的对数算得飞快,人称Log大侠.     一天,Log大侠的好友 drd 有一些整数序列需要变换,Log大侠正好施展法力... ...

  9. 创建、配置Servlet

    1.创建Servlet 2.选择继承的类及需要覆盖的方法 3.Servlet结构 package com.sysker.servlet; import java.io.IOException; imp ...

  10. cf837E(xjb)

    题目链接:http://codeforces.com/problemset/problem/837/E 题意:f(a, 0) = 0 ,     f(a, b) = 1 + f(a, b - gcd( ...