多閘道環境(如雙 WAN、4G 備援)下,主閘道失效時自動切換至備用閘道,保障主機持續聯網。腳本以 Ping 外網目標(預設 www.baidu.com)為健康檢查,失敗則隨機挑選 192.168.1.1~3 寫入 /etc/network/interfaces 並重啟網路服務。
#!/usr/bin/python
# auto change gateway - Created By mickelfeng
import os, random, re
gateway_base = 'gateway 192.168.1.'
rand = random.randint(1, 3) # 隨機挑選 1~3
test_target = 'www.baidu.com'
restart_cmd = '/etc/init.d/networking restart'
new_gw = "%s%d" % (gateway_base, rand)
ping_cmd = 'ping -c 3 ' + test_target
try:
ret = os.system(ping_cmd)
print("Ping return:", ret)
if ret != 0: # 非 0 表示失敗
# 讀取 interfaces 並替換 gateway 行
data = open('/etc/network/interfaces').read()
data = re.sub(r'gateway 192\.168\.1\.\d+', new_gw, data)
with open('/etc/network/interfaces', 'wb') as f:
f.write(data)
# 重啟網路服務兩次確保生效(舊系統有時需雙擊)
os.system(restart_cmd)
os.system(restart_cmd)
except Exception as e:
print("Error:", e)
pass
random.randint(1,3) 簡單輪換,避免單點故障;生產環境建議改為優先級輪詢或健康度評分。re.sub(r'gateway 192\.168\.1\.\d+', new_gw, data) 精確替換舊閘道行,保留其他配置(如 address、netmask)。open(..., 'wb') 避免 Python 2 自動換行轉換導致配置檔損壞。ifupdown 需雙次重啟才生效新閘道。except: pass 吞噬所有錯誤,生產務必改為記錄日誌並告警。#!/usr/bin/env python3
import subprocess, random, pathlib, sys
GW_CANDIDATES = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
TEST_HOST = '8.8.8.8'
IFACE = 'eth0'
NETPLAN = pathlib.Path('/etc/netplan/01-netcfg.yaml')
def ping_ok(host, count=3, timeout=2):
try:
subprocess.run(['ping', '-c', str(count), '-W', str(timeout), host],
check=True, capture_output=True)
return True
except subprocess.CalledProcessError:
return False
def update_gateway(new_gw):
# 假設 netplan YAML 結構:ethernets: {eth0: {gateway4: ...}}
import yaml
cfg = yaml.safe_load(NETPLAN.read_text())
cfg['network']['ethernets'][IFACE]['gateway4'] = new_gw
NETPLAN.write_text(yaml.dump(cfg))
subprocess.run(['netplan', 'apply'], check=True)
if __name__ == '__main__':
if ping_ok(TEST_HOST):
sys.exit(0)
for gw in random.sample(GW_CANDIDATES, len(GW_CANDIDATES)):
try:
update_gateway(gw)
if ping_ok(TEST_HOST):
print(f"Switched to {gw} OK")
sys.exit(0)
except Exception as e:
print(f"Try {gw} failed: {e}")
print("All gateways failed")
sys.exit(1)
/usr/local/bin/auto_gw.py,chmod +x。cron 或 systemd timer 每 1~5 分鐘執行一次。/var/log/auto_gw.log,配合 logrotate。nmcli con mod + nmcli con up 替換 netplan 邏輯。舊版腳本展示了「Ping 健檢 + 正則改配置 + 重啟網路」的經典自動化思路;現代版採用 subprocess、yaml、netplan 更健壯。核心邏輯不變:**偵測失效 → 選擇備援 → 原子更新配置 → 重載網路 → 驗證生效**。