萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Ruby 實現 GitHub Hosts 自動更新:突破網絡限制實戰

背景與原理

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

關鍵技術點

  1. open-uri:標準庫支援 HTTP/HTTPS/FTP 透明打開
  2. 權限提升:捕獲 Errno::EACCES 自動 sudo 重啟
  3. 原子寫入:File.open("w") 截斷重寫,避免部分寫入損壞
  4. 編碼聲明:# coding: utf-8 確保中文註釋正確解析

定時自動化部署

Cron 定時任務

# 編輯 crontab
sudo crontab -e

# 每天凌晨 3 點更新
0 3 * * * /usr/bin/ruby /path/to/update_hosts.rb >> /var/log/hosts_update.log 2>&1

Systemd Timer(現代 Linux 推薦)

```ini # /etc/systemd/system/update-hosts.service [Unit] Description=Update GitHub Hosts After=network-online.target Wants=network-online.target [Service] Type=oneshot ExecStart=/usr/bin/ruby /path/to/update_hosts.rb User=root ``` ```ini # /etc/systemd/system/update-hosts.timer [Unit] Description=Daily GitHub Hosts Update [Timer] OnCalendar=daily Persistent=true [Install] WantedBy=timers.target ```
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

適用場景擴展

  • Android 設備(需 Root):/system/etc/hosts
  • Windows:C:\Windows\System32\drivers\etc\hosts
  • 路由器(OpenWrt/梅林):/etc/hosts 或 dnsmasq 配置

自動化 Hosts 維護是開發者提升 GitHub 訪問體驗的實用技能,結合定時任務與完整性校驗可構建生產級解決方案。

copyright © 萬盛學電腦網 all rights reserved