Nameslio

Eric讨论 | 贡献2026年4月17日 (五) 12:18的版本 →‎使用API示例
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

Nameslio是一家域名注册商和网络托管公司。


API

使用API示例

使用python,添加或修改域名主机的A记录,如abc.abc.com设置ip为x.x.x.x:

import urllib.request
import urllib.parse
import json
import os

BASE_URL = "https://www.namesilo.com/api/"

# ========== 辅助函数 ==========
def load_dotenv(filepath=".env"):
    """手动解析 .env 文件"""
    if not os.path.exists(filepath):
        return
    with open(filepath, "r") as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if "=" in line:
                key, value = line.split("=", 1)
                os.environ[key.strip()] = value.strip().strip("\"'")

def check_success(res):
    code = res.get("reply", {}).get("code")
    if code != 300:
        raise Exception(f"API失败: code={code}, res={res}")
    else:
        # print(f'成功返回:{res["reply"].get("resource_record", [])}')
        return True

def _request(endpoint, params):
    api_key = os.getenv("NAMESILO_API_KEY")
    if not api_key:
        raise ValueError("请在 .env 中设置 NAMESILO_API_KEY")    
    params.update({
        "version": "1",
        "type": "json",  # 推荐用 json,比 xml 好处理
        "key": api_key
    })

    url = BASE_URL + endpoint + "?" + urllib.parse.urlencode(params)
    # 测试使用,链接含有APIkey
    # print(f"正在请求:{url}")

    req = urllib.request.Request(
        url,
        headers={
            "User-Agent": "Mozilla/5.0"  # 关键!
        }
    )

    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read().decode())


def upsert_a_record(domain, host, ip, ttl=3600):

    # 1️⃣ 查询记录
    res = _request("dnsListRecords", {
        "domain": domain
    })

    check_success(res)

    records = res["reply"].get("resource_record", [])
    if isinstance(records, dict):  # 只有一条时会是 dict
        records = [records]

    record_id = None

    # 2️⃣ 查找已有记录
    for r in records:
        if r["type"] == "A" and r["host"] == host:
            if r["value"] == ip:
                print("记录已存在, 无需更新")
                return True 
            record_id = r["record_id"]

    # 3️⃣ 更新
    if record_id:
        res = _request("dnsUpdateRecord", {
            "domain": domain,
            "rrid": record_id,
            "rrhost": host,
            "rrvalue": ip,
            "rrttl": ttl
        })

        check_success(res)

    # 4️⃣ 新增
    else:
        res = _request("dnsAddRecord", {
            "domain": domain,
            "rrtype": "A",
            "rrhost": host,
            "rrvalue": ip,
            "rrttl": ttl
        })

        check_success(res)

# ========== 使用示例 ==========

if __name__ == "__main__":
    # 加载 .env 文件
    load_dotenv()

    upsert_a_record(
        domain=os.getenv("DOMAIN"),   # 如: example.com
        host=os.getenv("SUBDOMAIN"),  # 如: www
        ip=os.getenv("IP_ADDRESS"),   # 如: 100.100.100.100 
    )

密钥不放程序文件里,放.env文件:

NAMESILO_API_KEY=xxx
DOMAIN=xxx
SUBDOMAIN=xxx
IP_ADDRESS=xxx