Nameslio

Eric讨论 | 贡献2026年4月17日 (五) 11:51的版本

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}")

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)
    print(f"正在请求:{url}")

    req = urllib.request.Request(
        url,
        headers={
            "User-Agent": "Mozilla/5.0"  # 不加请求头,namesilo会拒绝
        }
    )

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


def upsert_a_record(domain, host, ip, ttl=3600):
    full_host = f"{host}.{domain}" if host != "@" else domain

    # 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"] == full_host:
            record_id = r["record_id"]
            break

    # 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()
    
    # 配置参数
    DOMAIN = os.getenv("DOMAIN")
    SUBDOMAIN = os.getenv("SUBDOMAIN")
    IP_ADDRESS = os.getenv("IP_ADDRESS")  

    upsert_a_record(
        domain=DOMAIN,
        host=SUBDOMAIN,
        ip=IP_ADDRESS
    )

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

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