2011-04-20 131 views
13

如何以编程方式将应用程序或端口添加到Windows XP上的Windows防火墙?XP的Windows防火墙规则

+0

可能重复的[编程向Windows vista防火墙添加例外](http://stackoverflow.com/questions/1409896/programatically-add-exception-to-windows-vista-firewall) – 2011-04-20 13:34:38

+0

可能的重复[Add to防火墙例外列表](http://stackoverflow.com/questions/2384718/add-to-firewall-exception-list) – 2011-04-20 14:11:47

+2

这个答案只适用于XP。因为OP接受了这个及其有用的信息,所以不是一个骗局,因为重复的作品只在win7和vista中。 – 2012-07-07 22:09:31

回答

17

尝试从我们的开源SQlite3UI.pas部提取出验证码:

function GetXPFirewall(var fwMgr, profile: OleVariant): boolean; 
begin 
    Result := (Win32Platform=VER_PLATFORM_WIN32_NT) and 
    (Win32MajorVersion>5) or ((Win32MajorVersion=5) and (Win32MinorVersion>0)); 
    if result then // need Windows XP at least 
    try 
    fwMgr := CreateOleObject('HNetCfg.FwMgr'); 
    profile := fwMgr.LocalPolicy.CurrentProfile; 
    except 
    on E: Exception do 
     result := false; 
    end; 
end; 

const 
    NET_FW_PROFILE_DOMAIN = 0; 
    NET_FW_PROFILE_STANDARD = 1; 
    NET_FW_IP_VERSION_ANY = 2; 
    NET_FW_IP_PROTOCOL_UDP = 17; 
    NET_FW_IP_PROTOCOL_TCP = 6; 
    NET_FW_SCOPE_ALL = 0; 
    NET_FW_SCOPE_LOCAL_SUBNET = 1; 

procedure AddApplicationToXPFirewall(const EntryName, ApplicationPathAndExe: string); 
var fwMgr, profile, app: OleVariant; 
begin 
    if GetXPFirewall(fwMgr,profile) then 
    try 
    if profile.FirewallEnabled then begin 
     app := CreateOLEObject('HNetCfg.FwAuthorizedApplication'); 
     try 
     app.ProcessImageFileName := ApplicationPathAndExe; 
     app.Name := EntryName; 
     app.Scope := NET_FW_SCOPE_ALL; 
     app.IpVersion := NET_FW_IP_VERSION_ANY; 
     app.Enabled :=true; 
     profile.AuthorizedApplications.Add(app); 
     finally 
     app := varNull; 
     end; 
    end; 
    finally 
    profile := varNull; 
    fwMgr := varNull; 
    end; 
end; 

procedure AddPortToXPFirewall(const EntryName: string; PortNumber: cardinal); 
var fwMgr, profile, port: OleVariant; 
begin 
    if GetXPFirewall(fwMgr,profile) then 
    try 
    if profile.FirewallEnabled then begin 
     port := CreateOLEObject('HNetCfg.FWOpenPort'); 
     port.Name := EntryName; 
     port.Protocol := NET_FW_IP_PROTOCOL_TCP; 
     port.Port := PortNumber; 
     port.Scope := NET_FW_SCOPE_ALL; 
     port.Enabled := true; 
     profile.GloballyOpenPorts.Add(port); 
    end; 
    finally 
    port := varNull; 
    profile := varNull; 
    fwMgr := varNull; 
    end; 
end; 

它可以让你将应用程序或端口添加到XP防火墙。 应该从Delphi 6一直工作到XE。

+1

我已经更新了单元的源代码,可以在XP,Vista和Seven上运行,可以用于应用程序,也可以用于端口。请参阅http://synopse.info/forum/viewtopic.php?pid=4652#p4652 – 2012-07-11 06:51:16

6

脚本编写Windows防火墙是可能的,例如见Scripting the Windows Firewall

和代码示例here

+0

我使用Delphi 7! – 2011-04-20 10:03:14

+0

Delphi 7支持基于COM的脚本 – mjn 2011-04-20 10:06:01

+0

在这种情况下,您应该尝试导入类型库,请参阅我的链接,它提到类型库DLL文件通常位于“C:\ Windows \ System32 \ hnetcfg.dll” (这篇文章是关于XP的,我在Windows 7中检查过,并且有这个名字的文件存在) – mjn 2011-04-20 10:27:33

相关问题