如何在Worker角色实例上成功编辑代码中的防火墙规则?

我正在尝试一些在本地工作的代码但它在我的云实例上不起作用。 我假设它可能与权限相关,但我还无法修复它。 这是我在本地调试我的工作者角色时的工作原理,但是当它发布时没有任何反应(现在正在暂存)。

string strCmdText = string.Format("advfirewall firewall add rule name=\"BlockU\" protocol=any dir=in action=block remoteip={0}", ip); ProcessStartInfo psi = new ProcessStartInfo("netsh.exe", strCmdText); psi.RedirectStandardOutput = true; psi.UseShellExecute = false; psi.CreateNoWindow = true; try { Process.Start(psi); } catch (Exception ex) { Debug.WriteLine(ex.Message); } 

我也试过用

 psi.Verb = "runas"; 

但这也没有帮助。

最后我尝试了防火墙api。 这也在本地工作,但在最后一行上抛出了访问被拒绝错误。

 INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); inboundRule.Enabled = true; inboundRule.RemoteAddresses = ip; inboundRule.InterfaceTypes = "All"; inboundRule.Protocol = (int)NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY; inboundRule.Name = "BlockU Part 2"; //inboundRule.Profiles = currentProfiles; inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; // Now add the rule INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallPolicy.Rules.Add(inboundRule); 

我发现在azure论坛上我需要启用我的Worker Role以提升的权限运行。 这可以通过将以下属性添加到WorkerRole元素在ServiceDefinition.csdef文件中完成

  

并且还添加了一个

  

WorkerRole元素内的元素。

两组代码都已成功运行配置更改。

我在msdn博客中找到了一篇有趣的post,它使用了一个简化防火墙规则配置的库,可能会解决你的问题,

http://blogs.msdn.com/b/securitytools/archive/2009/08/21/automating-windows-firewall-settings-with-c.aspx

在…上