Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Python 腳本自動更新 Google Hosts (Windows 適用)

編輯:Linux 教學

從 smarthosts.googlecode.com 定期抓取最新 Google 服務 hosts 列表,自動合併至本機 C:\Windows\System32\drivers\etc\hosts,並備份原有內容。適用於 Windows XP/7,需 Python 2.7 環境。

腳本功能

  • 下載遠端 hosts 內容
  • 以正則 `#Google Services START ... #Google Services END` 擷取 Google 區塊
  • 移除本機 hosts 中舊的 Google 區塊
  • 將新區塊置於檔案開頭,其餘內容保留
  • 自動備份原 hosts 為 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()

使用說明

  1. 安裝 Python 2.7,確保 urllib2 可用。
  2. 將腳本存為 update_google_hosts.py。
  3. 以**系統管理員權限**執行 CMD,運行 python update_google_hosts.py。
  4. 執行成功後,hosts 檔案開頭將包含最新 Google 服務 IP 對應,原有其他條目保留。

排程自動化 (可選)

Windows 任務排程器 → 建立基本任務 → 觸發器設為每日/每週 → 動作:python.exe 參數:C:\path\to\update_google_hosts.py → 勾選「使用最高權限執行」。

注意事項

  • 來源網址 smarthosts.googlecode.com 可能已遷移,若失效請尋找最新維護的 hosts 專案 (如 GitHub 上的 googlehosts 專案) 並修改 updateUrl。
  • 修改 hosts 需管理員權限,否則寫入失敗。
  • 腳本為 Python 2 寫法,Python 3 需將 urllib2 改 urllib.request、raw_input 改 input、print 加括號。
Copyright © Windows教程網 All Rights Reserved