使用 Hosts 文件进行广告和间谍软件防护






3.17/5 (8投票s)
2006 年 1 月 11 日

52206

297
本文档介绍了如何使用 Hosts 文件来阻止广告和间谍软件。
引言
我编写了这个脚本来自动化更新 Hosts 文件的过程,Hosts 文件内容来自 http://www.someonewhocares.org/hosts/。 使用这个 Hosts 文件是我发现的“让互联网不再那么糟糕”的最佳方法,正如它所宣称的那样。
该 VBScript 脚本会将网页下载到本地临时文件,解析该文件以仅保留注释和所需行,然后将该文件放入正确的目录。 它还会创建 Hosts 文件的备份副本,并将新文件设置为只读。只需双击即可执行,或者如果删除了末尾的“一切顺利”回显,则可以将其作为 Windows 计划任务运行。 我已经在 Windows 2K、2003 和 XP 上测试过它。
预防胜于治疗,能够在不被“赢取免费 DVD 播放器”广告闪烁干扰的情况下使用 Hotmail 是无价的。 每个 IT 人员都应该使用这个!
代码
'Create objFSO and objIE objects
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objIE=WScript.createobject("internetexplorer.application")
'Determine path to hosts and set strHostsPath to correct path
dim bFolder, strHostsPath
bFolder = objFSO.folderExists("C:\WINDOWS\")
if bFolder = False then
strHostsPath = "C:\WINNT\system32\drivers\etc\"
else
strHostsPath = "C:\WINDOWS\system32\drivers\etc\"
End if
'Create Temp Web file here since
'it needs a few milliseconds to complete
Set TempWebFile = objFSO.CreateTextFile("C:\Temp.html", 2)
'Navigate and wait for page to load
objIE.Navigate ("http://someonewhocares.org/hosts/")
Wscript.Sleep 1000
'If sleep here omitted, an endless loop
'happens on windows 2003
'wait for IE to Download Page before continuing execution
While objIE.Busy: Wend
'Write contents of navigated webpage to local temp Web file
TempWebFile.Write objIE.Document.body.outerHTML
TempWebFile.close 'Close File
'open the local Webpage and read in all lines
set PageText = objFSO.GetFile("C:\temp.html")
set ts = pagetext.OpenAsTextStream(1,-2)
dim ResultLine,ResultComment,ReadLine
'40
'Create output file for parsed data from webpage
Set OutFile = objFSO.OpenTextFile("C:\temp.txt",2,True)
' FileMode = 1=read 2=Write 8=Append
Do while not ts.AtEndOfStream
ReadLine = ts.readline
ResultLine = InStr(Readline, "127.0.0.1")
ResultComment = InStr(Readline, "#")
'Weed out anything but Good lines,
' comments, and blanklines, and write temp file.
if (ResultLine = 1) or (ResultComment = 1) _
or (ReadLine = "") then
OutFile.WriteLine(ReadLine)
end if
Loop
ts.close
OutFile.close 'Close File
'Set host file to normal attributes from whatever it may be
Set objHostsFile = objFSO.GetFile(strHostsPath + "hosts")
objHostsFile.Attributes = 0
'Backup existing hosts file
set BackFile=objFSO.GetFile(strHostsPath + "hosts")
BackFile.Copy strHostsPath + "hosts.bak"
'Copy new hosts file
set NewFile=objFSO.GetFile("C:\temp.txt")
NewFile.Copy strHostsPath + "hosts"
'Delete Temp Files
set DeleteFile=objFSO.GetFile("C:\Temp.html")
DeleteFile.delete
NewFile.delete
'Set new host file attribute to read only
objHostsFile.Attributes = 1
WScript.Echo "Your Hosts File Has Been Updated Successfully!"