在 Linux 上用 Shell 函式自動更新 DuckDNS
前言
DuckDNS 是免費的 DDNS 服務,適合家用伺服器或 Raspberry Pi 等動態 IP 環境。本文介紹如何在 ~/.profile 中建立一個 Shell 函式,隨時手動執行更新,也可搭配 cron 排程自動執行。
前置作業
- 前往 duckdns.org 註冊並登入
- 建立一個子網域(例如
my-host) - 在頁面上方複製你的 token
設定函式
編輯 ~/.profile,加入以下函式:
duckdns() {
local result
local domain="my-host"
local token="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
result=$(echo url="https://www.duckdns.org/update?domains=${domain}&token=${token}&ip=&verbose=true" | curl -s -k -K -)
local status=$(echo "$result" | head -1)
local ip=$(echo "$result" | sed -n '2p')
if [ "$status" = "OK" ]; then
echo -e "\033[1;32m[OK] ${domain}.duckdns.org → ${ip}\033[0m"
else
echo -e "\033[1;31m[FAILED] ${domain}.duckdns.org update failed\033[0m"
return 1
fi
}
將 domain 和 token 替換成你自己的值。
使用方式
# 載入設定(僅首次需要,新開終端機會自動載入)
source ~/.profile
# 執行更新
duckdns
成功會顯示:
[OK] my-host.duckdns.org → 123.45.67.89
搭配 cron 自動排程
如果希望每 5 分鐘自動更新,執行 crontab -e 加入:
*/5 * * * * . $HOME/.profile; duckdns > /dev/null 2>&1
運作原理
- 使用 DuckDNS API 的
verbose=true參數,回傳更新狀態與實際註冊的 IP - 不帶
ip=參數時,DuckDNS 會自動偵測請求來源 IP - 函式會驗證 API 回傳狀態,成功顯示綠色,失敗顯示紅色

沒有留言:
張貼留言