如何使用Inno Setup修改Hosts文件:详细解决方案

随心笔谈10个月前发布 admin
86 0

对于想要修改 Hosts 文件的朋友来说我们除了自己手动定位到 Hosts 文件使用编辑器编辑外我们还可以通过批处理命令进行编辑。今天要给大家介绍的是通过使用 Inno Setup 安装包在安装程序的时候对 Hosts 进行修改以达到屏蔽某些应用程序访问某些服务器进行验证的效果。

Windows 主机文件存储 IP 地址和域名有助于将计算机定向到 Internet 或本地网络上的站点。 浏览 Web 通常不需要编辑 Hosts 文件,但是它是阻止有害站点的基本方法,还是一种将 Web 地址与正在开发中的网站绑定在一起的工具。 Hosts 文件设置不正确会导致网站停止加载,因此,如果您无法在线连接某些站点,请检查文件中的错误条目或清除其修改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#ifdef Unicode
#define A “W”
#else
#define A “A”
#endif

[code]
const
myMark = ‘由 gnatix 编写’;   // 作为标识

function GetFileAttributes(lpFileName: String)Cardinal;
external ‘GetFileAttributes{#A}@kernel32.dll stdcall’;

function SetFileAttributes(lpFileName: String; dwFileAttributes: Cardinal)Boolean;
external ‘SetFileAttributes{#A}@kernel32.dll stdcall’;

function LineInFile(sLine, fPath: string)Boolean;
var
aos: TArrayOfString;
n: Integer;
begin
Result:= false;
if LoadStringsFromFile(fPath, aos) then
for n:= 0 to GetArrayLength(aos)1 do
if aos[n] = sLine then
begin
Result := true;
Exit;
end;
end;

procedure AddHosts(newItem, comments: string);
var
OldFileAttribute: Cardinal;
hfPath, newLine: string;
begin
hfPath := ExpandConstant(‘{sys}\drivers\etc\hosts’);
if not LineInFile(newItem, hfPath) then       // 仅添加 Hosts 中还没有的项目
begin
OldFileAttribute:= GetFileAttributes(hfPath);
SetFileAttributes(hfPath, FILE_ATTRIBUTE_NORMAL);
newLine := newItem + ‘ # ‘ + myMark;
If comments > ‘ ‘ then
newLine := newLine + ‘ / ‘ + comments;
SaveStringToFile(hfPath, #13#10 + newLine, True);
SetFileAttributes(hfPath, OldFileAttribute);
end;
end;

procedure RemoveHosts(sItem: string);
var
OldFileAttribute: Cardinal;
hfPath, newLine: string;
stl: TStringList;
n: Integer;
begin
hfPath := ExpandConstant(‘{sys}\drivers\etc\hosts’);
newLine := sItem + ‘ # ‘ + myMark;
stl:= TStringList.Create;
stl.LoadFromFile(hfPath);
for n:= stl.Count1 downto 0 do
if Pos(newLine, stl.Strings[n]) = 1 then
stl.Delete(n);
OldFileAttribute:= GetFileAttributes(hfPath);
SetFileAttributes(hfPath, FILE_ATTRIBUTE_NORMAL);
stl.SaveToFile(hfPath);
stl.Free;
SetFileAttributes(hfPath, OldFileAttribute);
end;

procedure Initializewizard;
begin
AddHosts(‘0.0.0.0 www.xxx.com’‘这是注释’)// 在 Hosts 中添加新项目,带注释
AddHosts(‘0.0.0.0 www.111.com’);       // 在 Hosts 中添加新项目,不带注释
end;

procedure DeinitializeUninstall;
begin
RemoveHosts(‘0.0.0.0 www.xxx.com’)// 从 Hosts 中删除项目
RemoveHosts(‘0.0.0.0 www.111.com’);       // 从 Hosts 中删除项目
end;

把以上代码复制到 Inno Setup 脚本中保存或者根据您的需要再进行修改调整即可。

Windows hosts 文件的功能类似于 DNS 服务器的本地副本,因此如果您要进行自定义域重定向,阻止网站或删除由恶意软件设置的恶意条目,则知道如何进行编辑可能会派上用场。 也就是说,在某些 Windows 版本中对此文件进行更改时,您可能会遇到权限错误和其他问题。

© 版权声明

相关文章