c# - 如何在辅助角色实例上成功编辑代码中的防火墙规则?

标签 c# azure-worker-roles windows-firewall

我正在尝试一些在本地工作的代码,但它在我的云实例上不起作用。我认为这可能与权限相关,但我还无法修复它。这是我在本地调试工作角色时可以使用的内容,但在发布时(现在正在登台)没有任何反应。

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 forums 上找到了我需要使我的辅助角色能够以提升的权限运行。通过将以下属性添加到 WorkerRole 元素,可以在 ServiceDefinition.csdef 文件中完成此操作

<WorkerRole name="CloudService.Worker" vmsize="ExtraSmall"
            enableNativeCodeExecution="true">

还可以添加

<Runtime executionContext="elevated" />

WorkerRole 元素内的元素。

两组代码均通过配置更改成功运行。

关于c# - 如何在辅助角色实例上成功编辑代码中的防火墙规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32830531/

相关文章:

python - 我如何配置 python/flask 以使用 Windows 防火墙进行公共(public)访问

c# - 无法在 Xamarin.Android 项目中保存布局

azure - 无法启动Azure模拟器 "Operation not supported. Unknown error: 0x80070057."

c# - 使用 API 更新现有防火墙规则

azure - 对于 Azure 辅助角色,cscfg 文件和 App.config 文件如何相互关联?

Azure WorkerRole 在本地 dev-fabric 上运行,但不在 azure 上运行

windows-server - 以下 GPO 设置之间有什么区别?

c# - 在 asp.net 中动态生成 HTML 元素时缺少图像源

c# - 在解决方案的多个项目中引用共享项目

c# - 使用代码优先方法的可空枚举字段不会在数据库中创建枚举字段