從 smarthosts.googlecode.com 定期抓取最新 Google 服務 hosts 列表,自動合併至本機 C:\Windows\System32\drivers\etc\hosts,並備份原有內容。適用於 Windows XP/7,需 Python 2.7 環境。
#Google Services START ... #Google Services END` 擷取 Google 區塊hosts_bak
# -*- coding: utf-8 -*-
__author__ = 'xu.zhibin'
__createDateTime__ = '2012-06-25 11:54'
import os, sys, re, urllib2
updateUrl = "https://smarthosts.googlecode.com/svn/trunk/hosts"
hostPath = r"C:\WINDOWS\system32\drivers\etc\hosts"
pattern = re.compile(r"#Google Services START([\s\S]*)#Google Services END")
# 1. 取得最新 Google Hosts
try:
response = urllib2.urlopen(updateUrl)
updateContent = response.read()
except Exception as ex:
print "獲取最新 Google Hosts 失敗!"
raw_input()
sys.exit()
match = pattern.search(updateContent)
if not match:
print "遠端內容格式異常,未找到 Google 區塊。"
raw_input()
sys.exit()
googleContent = updateContent[match.start():match.end()]
# 2. 讀取本地 hosts
with open(hostPath, 'r+') as f:
hostContent = f.read()
# 3. 移除舊 Google 區塊並壓縮空行
bakContent = pattern.sub('', hostContent)
bakContent = re.sub(r"\n\n", "\n", bakContent)
# 4. 寫入新內容 (Google 區塊在最前)
newContent = googleContent + "\n" + bakContent
with open(hostPath, 'w') as f:
f.write(newContent)
# 5. 備份
bakPath = hostPath + "_bak"
with open(bakPath, 'w') as f:
f.write(bakContent)
print "更新 Hosts 成功!"
raw_input()
urllib2 可用。update_google_hosts.py。python update_google_hosts.py。hosts 檔案開頭將包含最新 Google 服務 IP 對應,原有其他條目保留。Windows 任務排程器 → 建立基本任務 → 觸發器設為每日/每週 → 動作:python.exe 參數:C:\path\to\update_google_hosts.py → 勾選「使用最高權限執行」。
smarthosts.googlecode.com 可能已遷移,若失效請尋找最新維護的 hosts 專案 (如 GitHub 上的 googlehosts 專案) 並修改 updateUrl。urllib2 改 urllib.request、raw_input 改 input、print 加括號。