获取Windows防火墙提示的控制台应用程序,而不是服务 [英] Get Windows Firewall prompt for console app but not service

查看:103
本文介绍了获取Windows防火墙提示的控制台应用程序,而不是服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有收到TCP和UDP从网络上的其他设备的流C#.NET应用程序。



当我运行它作为控制台应用程序,Windows防火墙的提示我说:Windows防火墙已阻止该程序的某些功能,它要求我允许vshost32.exe到网络上通信



我同意和应用程序工作正常



然而,当我运行应用程序作为服务(我有一个单独的控制台和服务包装)我没有得到任何这样的提示,我只能得到它,如果开关工作关闭防火墙。



这是预期的服务? ()



另外,我看过一些代码片段建议你可以例外手动添加到Windows防火墙列表中。这是只为控制台应用程序,否则将用于服务还工作吗?



我的一些代码,在此情况下,在端口上侦听是有用的...

  // 
//设置UDP监听
//
如果(协议==UDP)
{
m_udp =新UdpConn(RedwallReceiver UDP,m_local,新NETADDRESS());
m_udp.Receive(新VDataHandler(receiveData的));
}

//
//设置TCP监听
//
如果(协议==TCP)
{
m_listener =新的TcpListener(m_local);
m_listener.Start();
m_listener.BeginAcceptSocket(AcceptSocket,NULL);
}


解决方案

服务执行下受限的环境和允许有很少或与UI交互。他的回答涵盖了所有的推理,这里是如何实现相同的。



我会建议增加一个额外的项目到解决方案(我们称之为配置),它可以启动作为安装过程的一部分。至于我记得,添加规则的防火墙需要管理权限。具体操作步骤如下:




  • 创建的配置项目作为一个控制台或WinForms应用程序。这里需要无UI。

  • 添加应用程序清单文件的配置项目。右击项目,添加>新建项目>应用程序清单文件。更改< requestedExecutionLevel> 标签来读取< requestedExecutionLevel水平=requireAdministratoruiAccess =FALSE/>

  • 配置项目的输出添加到您的安装/部署项目。

  • 选择部署项目,并导航到自定义操作设置页。添加一个新的自定义操作提交节点下,使它指向配置项目的输出。

  • 配置项目,从COM引用添加到 NetFwTypeLib 引用。

  • 添加以下代码到配置项目。



修改配置项目的方法返回一个int(0表示成功,非零失败),并使用下面的代码。请注意,我从我的项目中粘贴此直接,所以你可能需要修正一些错误decleration等。

 私有静态诠释主要(字串[] args)
{
VAR应用=新NetFwAuthorizedApplication()
{
NAME =则将MyService,
启用=真,
RemoteAddresses =*,
范围= NET_FW_SCOPE_.NET_FW_SCOPE_ALL,
IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY,
ProcessImageFileName =ServiceAssemblyName.dll,
};

返回(FirewallUtilities.AddApplication(应用程序,出异常)?0:-1);
}

命名空间MySolution.Configurator.Firewall
{
使用系统;
使用System.Linq的;
使用NetFwTypeLib;

公共密封类NetFwAuthorizedApplication:
INetFwAuthorizedApplication
{
公共字符串名称{;组; }
公共BOOL启用{搞定;组; }
公共NET_FW_SCOPE_范围{搞定;组; }
公共字符串RemoteAddresses {搞定;组; }
公共字符串ProcessImageFileName {搞定;组; }
公共NET_FW_IP_VERSION_ IpVersion {搞定;组; }

公共NetFwAuthorizedApplication()
{
this.Name =;
this.Enabled = FALSE;
this.RemoteAddresses =;
this.ProcessImageFileName =;
this.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
this.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
}

公共NetFwAuthorizedApplication(字符串名称,启用布尔,字符串remoteAddresses,NET_FW_SCOPE_范围,NET_FW_IP_VERSION_ ipVersion,串processImageFileName)
{
this.Name =名称;
this.Scope =范围;
this.Enabled =启用;
this.IpVersion = ipVersion;
this.RemoteAddresses = remoteAddresses;
this.ProcessImageFileName = processImageFileName;
}

公共静态NetFwAuthorizedApplication FromINetFwAuthorizedApplication(INetFwAuthorizedApplication应用程序)
{
返回(新NetFwAuthorizedApplication(application.Name,application.Enabled,application.RemoteAddresses,application.Scope ,application.IpVersion,application.ProcessImageFileName));
}
}
} $ B使用系统
$ B命名空间MySolution.Configurator.Firewall
{
;
使用System.Collections.Generic;
使用System.Globalization;
使用System.Linq的;
使用NetFwTypeLib;

公共静态类FirewallUtilities
{
公共静态布尔GetApplication(字符串processImageFileName,出INetFwAuthorizedApplication应用,走出异常除外)
{
VAR的结果=假;
变种comObjects =新的堆栈<对象>();

例外= NULL;
应用= NULL;

如果(processImageFileName == NULL){掷(新ArgumentNullException(processImageFileName)); }
如果(processImageFileName.Trim()长度== 0){掷(新ArgumentException的(参数[processImageFileName]不能为空,processImageFileName)); }


{
变种类型= Type.GetTypeFromProgID(HNetCfg.FwMgr,真正的);


{
VAR经理=(INetFwMgr)Activator.CreateInstance(类型);
comObjects.Push(经理);


{
VAR政策= manager.LocalPolicy;
comObjects.Push(政策);

无功配置= policy.CurrentProfile;
comObjects.Push(配置文件);

VAR应用= profile.AuthorizedApplications;
comObjects.Push(应用程序);

的foreach(在应用程序INetFwAuthorizedApplication)
{
comObjects.Push(应用程序);

如果(的String.Compare(app.ProcessImageFileName,processImageFileName,真实,CultureInfo.InvariantCulture)== 0)
{
结果=真;
应用= NetFwAuthorizedApplication.FromINetFwAuthorizedApplication(应用程序);

中断;
}
}

如果(结果!){掷(新的异常(请求的应用程序没有被发现。)); }
}
赶上(例外五)
{
例外= E;
}
}
赶上(例外五)
{
例外= E;
}
终于
{
,而(comObjects.Count大于0)
{
ComUtilities.ReleaseComObject(comObjects.Pop());
}
}
}
赶上(例外五)
{
例外= E;
}
终于
{
}

返回(结果);
}

公共静态布尔AddApplication(INetFwAuthorizedApplication应用,走出异常除外)
{
VAR的结果=假;
变种comObjects =新的堆栈<对象>();

例外= NULL;

如果(应用程序== NULL){掷(新ArgumentNullException(应用程序)); }


{
变种类型= Type.GetTypeFromProgID(HNetCfg.FwMgr,真正的);


{
VAR经理=(INetFwMgr)Activator.CreateInstance(类型);
comObjects.Push(经理);


{
VAR政策= manager.LocalPolicy;
comObjects.Push(政策);

无功配置= policy.CurrentProfile;
comObjects.Push(配置文件);

VAR应用= profile.AuthorizedApplications;
comObjects.Push(应用程序);

applications.Add(应用);

结果=真;
}
赶上(例外五)
{
例外= E;
}
}
赶上(例外五)
{
例外= E;
}
终于
{
,而(comObjects.Count大于0)
{
ComUtilities.ReleaseComObject(comObjects.Pop());
}
}
}
赶上(例外五)
{
例外= E;
}
终于
{
}

返回(结果);
}

公共静态布尔RemoveApplication(字符串processImageFileName,出异常除外)
{
VAR的结果=假;
变种comObjects =新的堆栈<对象>();

例外= NULL;

如果(processImageFileName == NULL){掷(新ArgumentNullException(processImageFileName)); }
如果(processImageFileName.Trim()长度== 0){掷(新ArgumentException的(参数[processImageFileName]不能为空,processImageFileName)); }


{
变种类型= Type.GetTypeFromProgID(HNetCfg.FwMgr,真正的);


{
VAR经理=(INetFwMgr)Activator.CreateInstance(类型);
comObjects.Push(经理);


{
VAR政策= manager.LocalPolicy;
comObjects.Push(政策);

无功配置= policy.CurrentProfile;
comObjects.Push(配置文件);

VAR应用= profile.AuthorizedApplications;
comObjects.Push(应用程序);

applications.Remove(processImageFileName);

结果=真;
}
赶上(例外五)
{
例外= E;
}
}
赶上(例外五)
{
例外= E;
}
终于
{
,而(comObjects.Count大于0)
{
ComUtilities.ReleaseComObject(comObjects.Pop());
}
}
}
赶上(例外五)
{
例外= E;
}
终于
{
}

返回(结果);
}
}
}


I have a c# .NET app that receives TCP and UDP streams from other devices on the network.

When I run it as console app, the Windows Firewall prompts me: "Windows Firewall has blocked some features of this program" and it ask me to allow vshost32.exe to communicate on the network.

I agree and the app works fine.

However when I run the app as a service (I have a separate console and service wrappers) I get no such prompt and I can only get it to work if switch off the firewall.

Is this expected for services? ()

Also, I have read some code snippets that suggest you can manually add exceptions to Windows Firewall list. Is this just for console apps or will it work for services also?

Some my code that listens on the ports in case this is usefull...

        //
        // Setup UDP listening
        //
        if (protocol == "UDP")
        {
            m_udp = new UdpConn("RedwallReceiver UDP", m_local, new NetAddress());
            m_udp.Receive(new VDataHandler(ReceiveData));
        }

        //
        // Setup TCP listening
        //
        if (protocol == "TCP")
        {
            m_listener = new TcpListener(m_local);
            m_listener.Start();
            m_listener.BeginAcceptSocket(AcceptSocket, null);
        }

解决方案

Services execute under restricted environments and are allowed to have very little or no interaction with the UI. His answer covers all the reasoning and here is how to achieve the same.

I would recommend adding an additional project to your solution (let's call it Configurator) which can be launched as part of the installation process. As far as I remember, adding a rule to the firewall requires administrative privileges. Here are the steps:

  • Create the Configurator project as a Console or WinForms application. No UI is needed here.
  • Add an application manifest file to the Configurator project. right-click project, Add > New Item > Application Manifest File. Change the <requestedExecutionLevel> tag to read <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />.
  • Add the output of the Configurator project to your setup/deployment project.
  • Select the deployment project and navigate to the Custom Actions tab. Add a new custom action under the Commit node and make it point to the output of the Configurator project.
  • In the Configurator project, add a reference to NetFwTypeLib from COM references.
  • Add the code below to the Configurator project.

Modify the Main method of the Configurator project to return an int (0 for success, non-zero for failure) and use the following code. Note that I've pasted this from my project directly so you may need to fix some decleration errors, etc.

private static int Main (string [] args)
{
    var application = new NetFwAuthorizedApplication()
    {
        Name = "MyService",
        Enabled = true,
        RemoteAddresses = "*",
        Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL,
        IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY,
        ProcessImageFileName = "ServiceAssemblyName.dll",
    };

    return (FirewallUtilities.AddApplication(application, out exception) ? 0 : -1);
}

namespace MySolution.Configurator.Firewall
{
    using System;
    using System.Linq;
    using NetFwTypeLib;

    public sealed class NetFwAuthorizedApplication:
        INetFwAuthorizedApplication
    {
        public string Name { get; set; }
        public bool Enabled { get; set; }
        public NET_FW_SCOPE_ Scope { get; set; }
        public string RemoteAddresses { get; set; }
        public string ProcessImageFileName { get; set; }
        public NET_FW_IP_VERSION_ IpVersion { get; set; }

        public NetFwAuthorizedApplication ()
        {
            this.Name = "";
            this.Enabled = false;
            this.RemoteAddresses = "";
            this.ProcessImageFileName = "";
            this.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
            this.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
        }

        public NetFwAuthorizedApplication (string name, bool enabled, string remoteAddresses, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion, string processImageFileName)
        {
            this.Name = name;
            this.Scope = scope;
            this.Enabled = enabled;
            this.IpVersion = ipVersion;
            this.RemoteAddresses = remoteAddresses;
            this.ProcessImageFileName = processImageFileName;
        }

        public static NetFwAuthorizedApplication FromINetFwAuthorizedApplication (INetFwAuthorizedApplication application)
        {
            return (new NetFwAuthorizedApplication(application.Name, application.Enabled, application.RemoteAddresses, application.Scope, application.IpVersion, application.ProcessImageFileName));
        }
    }
}

namespace MySolution.Configurator.Firewall
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using NetFwTypeLib;

    public static class FirewallUtilities
    {
        public static bool GetApplication (string processImageFileName, out INetFwAuthorizedApplication application, out Exception exception)
        {
            var result = false;
            var comObjects = new Stack<object>();

            exception = null;
            application = null;

            if (processImageFileName == null) { throw (new ArgumentNullException("processImageFileName")); }
            if (processImageFileName.Trim().Length == 0) { throw (new ArgumentException("The argument [processImageFileName] cannot be empty.", "processImageFileName")); }

            try
            {
                var type = Type.GetTypeFromProgID("HNetCfg.FwMgr", true);

                try
                {
                    var manager = (INetFwMgr) Activator.CreateInstance(type);
                    comObjects.Push(manager);

                    try
                    {
                        var policy = manager.LocalPolicy;
                        comObjects.Push(policy);

                        var profile = policy.CurrentProfile;
                        comObjects.Push(profile);

                        var applications = profile.AuthorizedApplications;
                        comObjects.Push(applications);

                        foreach (INetFwAuthorizedApplication app in applications)
                        {
                            comObjects.Push(app);

                            if (string.Compare(app.ProcessImageFileName, processImageFileName, true, CultureInfo.InvariantCulture) == 0)
                            {
                                result = true;
                                application = NetFwAuthorizedApplication.FromINetFwAuthorizedApplication(app);

                                break;
                            }
                        }

                        if (!result) { throw (new Exception("The requested application was not found.")); }
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                }
                finally
                {
                    while (comObjects.Count > 0)
                    {
                        ComUtilities.ReleaseComObject(comObjects.Pop());
                    }
                }
            }
            catch (Exception e)
            {
                exception = e;
            }
            finally
            {
            }

            return (result);
        }

        public static bool AddApplication (INetFwAuthorizedApplication application, out Exception exception)
        {
            var result = false;
            var comObjects = new Stack<object>();

            exception = null;

            if (application == null) { throw (new ArgumentNullException("application")); }

            try
            {
                var type = Type.GetTypeFromProgID("HNetCfg.FwMgr", true);

                try
                {
                    var manager = (INetFwMgr) Activator.CreateInstance(type);
                    comObjects.Push(manager);

                    try
                    {
                        var policy = manager.LocalPolicy;
                        comObjects.Push(policy);

                        var profile = policy.CurrentProfile;
                        comObjects.Push(profile);

                        var applications = profile.AuthorizedApplications;
                        comObjects.Push(applications);

                        applications.Add(application);

                        result = true;
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                }
                finally
                {
                    while (comObjects.Count > 0)
                    {
                        ComUtilities.ReleaseComObject(comObjects.Pop());
                    }
                }
            }
            catch (Exception e)
            {
                exception = e;
            }
            finally
            {
            }

            return (result);
        }

        public static bool RemoveApplication (string processImageFileName, out Exception exception)
        {
            var result = false;
            var comObjects = new Stack<object>();

            exception = null;

            if (processImageFileName == null) { throw (new ArgumentNullException("processImageFileName")); }
            if (processImageFileName.Trim().Length == 0) { throw (new ArgumentException("The argument [processImageFileName] cannot be empty.", "processImageFileName")); }

            try
            {
                var type = Type.GetTypeFromProgID("HNetCfg.FwMgr", true);

                try
                {
                    var manager = (INetFwMgr) Activator.CreateInstance(type);
                    comObjects.Push(manager);

                    try
                    {
                        var policy = manager.LocalPolicy;
                        comObjects.Push(policy);

                        var profile = policy.CurrentProfile;
                        comObjects.Push(profile);

                        var applications = profile.AuthorizedApplications;
                        comObjects.Push(applications);

                        applications.Remove(processImageFileName);

                        result = true;
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                }
                finally
                {
                    while (comObjects.Count > 0)
                    {
                        ComUtilities.ReleaseComObject(comObjects.Pop());
                    }
                }
            }
            catch (Exception e)
            {
                exception = e;
            }
            finally
            {
            }

            return (result);
        }
    }
}

这篇关于获取Windows防火墙提示的控制台应用程序,而不是服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆