【发布时间】:2011-08-09 08:51:05
【问题描述】:
如何在 Windows XP 上以编程方式将应用程序或端口添加到 Windows 防火墙?
【问题讨论】:
-
此答案仅适用于 xp。由于 OP 接受了这个及其有用的信息,因此编辑了标题,因此不是欺骗,因为重复的作品仅在 win7 和 vista 中有效。
标签: windows delphi winapi delphi-7 windows-firewall
如何在 Windows XP 上以编程方式将应用程序或端口添加到 Windows 防火墙?
【问题讨论】:
标签: windows delphi winapi delphi-7 windows-firewall
试试这个从我们的开源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。
【讨论】:
可以编写 Windows 防火墙脚本,请参阅 Scripting the Windows Firewall
还有代码示例,例如here
【讨论】:
is usually located in "C:\Windows\System32\hnetcfg.dll"(这篇文章是关于XP的,我在Windows 7中检查了一个文件有这个名字)
tlibimp -P c:\windows\system32\hnetcfg.dll - 但是查看它的内容我不确定这是否是正确的文件