中華電信每隔一段時間就會更新一次公開 IP,家裡的 VPN 就會失效,兩個方法固定 IP 位置:

  1. 向中華電信申請一個靜態 IP
  2. 利用 domain 指向 IP,用 crontab 定期自動更新 record

我的 domain 是在 Gandi 買的,Gandi 提供的服務叫 LiveDNS,但主網域已經用在別的地方,所以用 subdomain 進行設定。

申請 API Key

在 https://account.gandi.net/ 的 Security 裡申請
(https://api.gandi.net/docs/livedns/ Step 1)

POST method 建立文件取得 uuid

(https://api.gandi.net/docs/livedns/ Step 2)

$APIKEY 換成上一步驟申請的, $your_domain 換成自己的主網域,即便是要用子網域設定,這邊要帶入的是主網域,他是要建立這個網域的 DNS Record 資料

$ curl -D- -X POST -H "Content-Type: application/json" \
             -H "X-Api-Key: $APIKEY" \
             -d '{"name": "$your_domain Zone"}' \
             https://dns.api.gandi.net/api/v5/zones

回應 201 Created,Location Header 後面的 uuid 要記下來

這時候可以先驗證一下是否已經可以拉到目前的 DNS Record:

$ curl -H"X-Api-Key: $APIKEY" \
       https://dns.api.gandi.net/api/v5/domains/$your_domain/records

得到目前的 DNS Record 表示到目前為止都正確

自動取得對外 IP 並更新 DNS Record

這邊我是先去 Gandi 手動新增目前的對外 IP,並先測試了一下這樣的設定 VPN 會通,所以接著就直接用 python 拉對外 IP,用 PUT Method 向 Gandi 更新紀錄

#!/usr/bin/env python

import urllib3
from requests import get
import requests

ip = get('https://api.ipify.org').content.decode('utf8')

headers = {'X-Api-Key': $APILEY,'Content-Type':'application/json'}

data='{"rrset_type": "A", "rrset_ttl": 300, "rrset_name": $your_subdomain_name,"rrset_values": ["' + ip + '"]}'

r = requests.put('https://dns.api.gandi.net/api/v5/domains/$your_domain/records/$your_subdomain_name/A', data=data,headers=headers)
print(r.text)

最後寫進 crontab,設定參考:https://blog.gtwang.org/linux/linux-crontab-cron-job-tutorial-and-examples/

arrow
arrow
    文章標籤
    LiveDNS Gandi
    全站熱搜
    創作者介紹
    創作者 Elmo 的頭像
    Elmo

    ElMO

    Elmo 發表在 痞客邦 留言(0) 人氣()