华为域名动态更新ddns脚本 ipv6

作者:15354045@qq.com


# linux系统 cron 定时更新[ */5 * * * * python3  /home/ip6.py &> /dev/null; ]
# coding=utf-8
# 需要安装包 pip install requests
import os
import requests
from apig_sdk import signer
import re
import json
import subprocess
import socket
# 本地外网网卡,修改为自己的 
eth ="enp3s0"
name="ip6"
zoneID="xxxxxxxxxxx"
recordID="xxxxxxxxxxxxx"
saveipfile="/run/shm/"+recordID
URL="https://dns.cn-east-3.myhuaweicloud.com/v2"
IP =""
# 
def get_ipv6():
    child=subprocess.Popen("ip -6 addr show  "+eth+" | grep mngtmpaddr" ,shell=True, stdout = subprocess.PIPE)
    out=child.communicate();#保存 ip 中的所有信息
    ipv6_pattern='([2408|2409|240e]([a-f0-9]{1,4}:){7}[a-f0-9]{1,4})/64'
    m=re.findall(ipv6_pattern,str(out))
    return m[0][0]
    
# 利用socket库附带的校验功能实现校验。
def is_ipv6(ip):
    try:
        socket.inet_pton(socket.AF_INET6, ip)
    except socket.error:  # not a valid ip
        return False
    return True
if __name__ == '__main__':
    sig = signer.Signer()
    # Set the AK/SK to sign and authenticate the request.
    # 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;
    # 本示例以ak和sk保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。
    sig.Key = os.getenv('HUAWEICLOUD_SDK_AK')
    sig.Secret = os.getenv('HUAWEICLOUD_SDK_SK')
    # The following example shows how to set the request URL and parameters to query a VPC list.
    # Set request Endpoint.
    # Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH.
    # Set request URI.
    # Set parameters for the request URL.
    r = signer.HttpRequest("PUT", URL+"/zones/"+zoneID+"/recordsets/"+recordID)
    # Add header parameters, for example, x-domain-id for invoking a global service and x-project-id for invoking a project-level service.
    r.headers = {"content-type": "application/json"}
    # 查找外网ip地址
    IP=get_ipv6()
    # 如果是ipv6地址
    if is_ipv6(IP):
        fh = open(saveipfile, 'a+')
        fh.seek(0,0)
        oldip=fh.read()
        fh.close()
        # 如果查询得到的ip地址与上次更新的ip不一样,更新它
        if IP!=oldip:
            r.body = "{\"records\":[\""+IP+"\"]}"
            sig.Sign(r)
            resp = requests.request(r.method, r.scheme + "://" + r.host + r.uri, headers=r.headers, data=r.body)
            upip=json.loads(resp.content)['records'][0]
            fh = open(saveipfile, 'w')
            fh.write(upip)
            fh.close()
 

下载:ip6.py