GitHub 在國內訪問不穩定,通過修改 /etc/hosts 綁定可用 IP 可顯著提升訪問速度。本腳本自動從 GitHub Raw 獲取最新 hosts 內容並寫入系統文件(需 root 權限)。
#!/usr/bin/ruby
# coding: utf-8
require 'open-uri'
# GitHub hosts 維護項目(需確認項目存活性)
HOSTS_URL = "https://raw.githubusercontent.com/vokins/simpleu/master/hosts"
begin
# 寫入 /etc/hosts 需 root 權限
File.open("/etc/hosts", "w") do |f|
f.write URI.open(HOSTS_URL).read
end
puts "✅ Hosts 更新成功!"
rescue Errno::EACCES
puts "❌ 權限不足,嘗試以 sudo 重新運行..."
exec "sudo ruby #{$0} #{ARGV.join(' ')}"
rescue => e
puts "❌ 更新失敗: #{e.message}"
exit 1
end
Errno::EACCES 自動 sudo 重啟File.open("w") 截斷重寫,避免部分寫入損壞# coding: utf-8 確保中文註釋正確解析# 編輯 crontab
sudo crontab -e
# 每天凌晨 3 點更新
0 3 * * * /usr/bin/ruby /path/to/update_hosts.rb >> /var/log/hosts_update.log 2>&1
sudo systemctl daemon-reload
sudo systemctl enable --now update-hosts.timer
require 'open-uri'
require 'digest'
HOSTS_URL = "https://raw.githubusercontent.com/..."
LOCAL_PATH = "/etc/hosts"
BACKUP_PATH = "/etc/hosts.bak"
EXPECTED_SHA256 = "..." # 可選:預期內容哈希驗證
def update_hosts
# 1. 備份原文件
FileUtils.cp(LOCAL_PATH, BACKUP_PATH) if File.exist?(LOCAL_PATH)
# 2. 下載新內容
content = URI.open(HOSTS_URL,
"User-Agent" => "Ruby-Hosts-Updater/1.0",
read_timeout: 10
).read
# 3. 完整性校驗(可選)
if EXPECTED_SHA256 && Digest::SHA256.hexdigest(content) != EXPECTED_SHA256
raise "內容哈希不匹配,疑似劫持!"
end
# 4. 基本格式驗證
unless content.include?("github.com") && content =~ /^\d+\.\d+\.\d+\.\d+/
raise "內容格式異常,拒絕寫入"
end
# 5. 原子寫入
File.write(LOCAL_PATH, content)
puts "✅ 更新完成"
rescue => e
puts "❌ 失敗: #{e.message}"
# 6. 回滾
FileUtils.mv(BACKUP_PATH, LOCAL_PATH) if File.exist?(BACKUP_PATH)
exit 1
end
/system/etc/hostsC:\Windows\System32\drivers\etc\hosts/etc/hosts 或 dnsmasq 配置自動化 Hosts 維護是開發者提升 GitHub 訪問體驗的實用技能,結合定時任務與完整性校驗可構建生產級解決方案。