Delphi 7 Windows Vista/7防火墙例外网络位置

5

我有一段代码,是根据http://www.activexperts.com/activmonitor/windowsmanagement/scripts/networking/windowsfirewall/找到并实现的。

procedure AddExceptionToFirewall (Caption: String; Executable: String);
var
  FirewallMsg: OleVariant;
  Application: OleVariant;
  CurrentProfile: OleVariant;
begin
  FirewallMsg:= CreateOLEObject ('HNetCfg.FwMgr');
  CurrentProfile:= FirewallMsg.LocalPolicy.CurrentProfile;
  Application:= CreateOLEObject ('HNetCfg.FwAuthorizedApplication');
  Application.ProcessImageFileName:= Executable;
  Application.Name:= Caption;
  Application.Scope:= FW_SCOPE_ALL;
  Application.IpVersion:= FW_IP_VERSION_ANY;
  Application.Enabled:= True;
  CurrentProfile.AuthorizedApplications.Add (Application);
end;

问题在于,在Windows 7上,它只将异常添加为Public,而不是Private,如您在此处用 RED 圈出的那样。

enter image description here

仅设置为Public时,我的程序无法通过FTP连接访问我的主机,从而使我的程序无用。 这个问题只在Windows Vista/7上特别存在;在XP上,当前配置可以正常工作。

如果您有任何线索或有用的指针,请分享。

1个回答

9
从Windows Vista开始,您必须使用 INetFwPolicy2INetFwRule 接口才能访问新的防火墙功能。
尝试此示例,它会在公共和私有配置文件中添加一个新规则。
procedure AddExceptionToFirewall(Const Caption, Executable: String);
const
NET_FW_PROFILE2_DOMAIN  = 1;
NET_FW_PROFILE2_PRIVATE = 2;
NET_FW_PROFILE2_PUBLIC  = 4;

NET_FW_IP_PROTOCOL_TCP = 6;
NET_FW_ACTION_ALLOW    = 1;
var
  fwPolicy2      : OleVariant;
  RulesObject    : OleVariant;
  Profile        : Integer;
  NewRule        : OleVariant;
begin
  Profile             := NET_FW_PROFILE2_PRIVATE OR NET_FW_PROFILE2_PUBLIC;
  fwPolicy2           := CreateOleObject('HNetCfg.FwPolicy2');
  RulesObject         := fwPolicy2.Rules;
  NewRule             := CreateOleObject('HNetCfg.FWRule');
  NewRule.Name        := Caption;
  NewRule.Description := Caption;
  NewRule.Applicationname := Executable;
  NewRule.Protocol := NET_FW_IP_PROTOCOL_TCP;
  NewRule.Enabled := TRUE;
  NewRule.Profiles := Profile;
  NewRule.Action := NET_FW_ACTION_ALLOW;
  RulesObject.Add(NewRule);
end;

哇,这个很好用,它甚至可以手动渲染防火墙的私有和公共策略,使其无法删除!非常感谢RRUZ! - ziGi
如果CreateOleObject返回nil怎么办?顺便问一下,有没有MSDN页面介绍CreateOleObject的文档,它能返回什么,不能返回什么? - Arioch 'The
1
@Arioch'The,CreateOleObject 函数内部使用了 CoCreateInstance WinApi 方法,并且所有的错误代码都是使用 OleCheck 方法捕获的,所以如果出现任何错误,都会抛出异常。 - RRUZ
谢谢RRUZ,这是可直接使用的代码。这个代码需要以管理员权限运行吗? - Edwin Yip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接