[英]Can I get the firewall's status by c# code?
我可以通过 c# 代码获取防火墙状态吗? 当他的防火墙被阻止时,我想通知用户
您可以通过WMI进行操作,因为任何防火墙都必须通过WMI报告其状态(这是安全中心显示状态的方式)。
互联网上的信息很少,这些可能是起点:
http://msdn2.microsoft.com/en-us/library/ms950397.aspx
下一步是在C#中访问WMI类:
http://www.csharphelp.com/2006/10/wmi-made-easy-for-c/
http://geekswithblogs.net/PsychoCoder/archive/2008/01/25/using_wmi_in_csharp.aspx
......还有很多其他人,只是google“C#WMI”。
您可以使用以下链接与Windows防火墙进行交互。 包括NetFwTypeLib作为项目的引用。
对于Window Firewall,您可以使用以下代码创建管理器:
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr manager= (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
从那里你可以阅读有关使用Windows防火墙配置的各种方法。
Windows防火墙(Windows XP ...限制Vista和7支持) http://msdn.microsoft.com/en-us/library/aa366452(v=VS.85 ) .aspx
具有高级安全性的Windows防火墙(Windows Vista / 7)
msdn.microsoft.com/en-us/library/aa366459(v=VS.85).aspx
假设您有3个标签,这将显示表单应用程序中所有防火墙的状态。
using System.Diagnostics;
private string getFirewallStatus()
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
if (process != null)
{
process.StandardInput.WriteLine("netsh advfirewall show allprofiles | find \"State\"");
process.StandardInput.Close();
string outputString = process.StandardOutput.ReadToEnd();
int count = 0;
for (int i = 0; i < outputString.Length - 3; i++)
{
if (outputString.Substring(i, 3).CompareTo(@"OFF") == 0)
{
count++;
switch (count)
{
case 1: label16.Text = "Off"; label16.ForeColor = System.Drawing.Color.Green; break;
case 2: label17.Text = "Off"; label17.ForeColor = System.Drawing.Color.Green; break;
case 3: label18.Text = "Off"; label18.ForeColor = System.Drawing.Color.Green; break;
default: MessageBox.Show("Firewall status unable to be found!"); break;
}
}
else if (outputString.Substring(i, 2).CompareTo("ON") == 0)
{
count++;
}
}
count = 0;
return outputString;
}
return string.Empty;
}
在Windows 7计算机上,我这样做是为了检测计算机是否启用了Windows防火墙。 我采取与迪伦建议相同的方法。
只需记住添加对Microsoft.TeamFoundation.Common
的引用。
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
bool firewallEnabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled;
我想看看这个任务的WMI解决方案,但这对我来说效果很好。
可以使用 Windows 安全中心 API。 https://learn.microsoft.com/en-us/windows/win32/api/wscapi/
[DllImport("wscapi.dll")]
private static extern int WscGetSecurityProviderHealth(int inValue, ref int outValue);
var outValue = -1;
var commandResultCode = WscGetSecurityProviderHealth(1, ref outValue);
if (commandResultCode > 0)
{
return outValue == 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.