[英]How to check a rule in windows firewall?
I would like to check if a port is open in the Windows firewall. 我想检查Windows防火墙中是否打开了一个端口。
I found this way using netsh: 我发现这种方式使用netsh:
netsh advfirewall firewall show rule name="My rule"
which will return if the rule exists or not... 如果规则存在与否将返回...
But, depending on Windows language, this will return different messages. 但是,根据Windows语言,这将返回不同的消息。 I am trying to solve this in a better way.
我试图以更好的方式解决这个问题。 I would like to have a result
Yes
or No
, True
or False
, not a localized string. 我想有一个结果
Yes
或No
, True
或False
,而不是一个本地化的字符串。
Do you have any tips?? 你有什么秘诀吗??
AS: the "advfirewall" command and underlying service were introduced in Windows Vista. AS:Windows Vista中引入了“advfirewall”命令和底层服务。 Windows 2000/XP do not have it and to support it you should use different interfaces.
Windows 2000 / XP没有它,为了支持它,你应该使用不同的接口。
Same goes for the computers with third-party, non-Microsoft firewalls installed (as part of antivirus suite for example). 安装了第三方非Microsoft防火墙的计算机也是如此(例如,作为防病毒套件的一部分)。
In general on Vista+ you should obtain INetFwRules COM object, then enumerate all the rules in it, and check every rule if it covers the port you are about. 通常在Vista +上你应该获得INetFwRules COM对象,然后枚举其中的所有规则,并检查每个规则是否覆盖了你所关注的端口。
Follows example to obtain and enumerate the rules https://theroadtodelphi.com/2013/11/21/using-the-windows-firewall-with-advanced-security-scripting-api-and-delphi/#Enumerating Firewall Rules 按照示例获取并枚举规则https://theroadtodelphi.com/2013/11/21/using-the-windows-firewall-with-advanced-security-scripting-api-and-delphi/#Enumerating防火墙规则
var
CurrentProfiles : Integer;
fwPolicy2 : OleVariant;
RulesObject : OleVariant;
rule : OleVariant;
oEnum : IEnumvariant;
iValue : LongWord;
fwPolicy2 := CreateOleObject('HNetCfg.FwPolicy2');
RulesObject := fwPolicy2.Rules;
CurrentProfiles := fwPolicy2.CurrentProfileTypes;
.....
Writeln('Rules:');
oEnum := IUnknown(Rulesobject._NewEnum) as IEnumVariant;
while oEnum.Next(1, rule, iValue) = 0 do
begin
if (rule.Profiles And CurrentProfiles)<>0 then
begin
Writeln(' Rule Name: ' + rule.Name);
Writeln(' ----------------------------------------------');
Writeln(' Description: ' + rule.Description);
Writeln(' Application Name: ' + rule.ApplicationName);
Writeln(' Service Name: ' + rule.ServiceName);
if (rule.Protocol = NET_FW_IP_PROTOCOL_TCP) or (rule.Protocol = NET_FW_IP_PROTOCOL_UDP) then
begin
Writeln(' Local Ports: ' + rule.LocalPorts);
Writeln(' Remote Ports: ' + rule.RemotePorts);
Writeln(' LocalAddresses: ' + rule.LocalAddresses);
Writeln(' RemoteAddresses: ' + rule.RemoteAddresses);
end;
.....
end;
OTOH using static binding rather than OleVariant should be faster and more reliable, check https://github.com/yypbd/yypbd-Delphi-HeaderPorting/tree/master/example/FirewallExample OTOH使用静态绑定而不是OleVariant应该更快更可靠,请查看https://github.com/yypbd/yypbd-Delphi-HeaderPorting/tree/master/example/FirewallExample
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.