OpenFirewall

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);
        }

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

posted @ 2018-04-04 13:59  寒夜美美  阅读(334)  评论(0编辑  收藏  举报