华为域名动态更新脚本ipv4

作者:15354045@qq.com
# coding=utf-8
# 需要安装包 pip install requests
import os
import requests
from apig_sdk import signer
import re
import json
name="ip4"
zoneID="xxxxxxxxxxx"
recordID="xxxxxxxxxx"
saveipfile="/run/shm/"+recordID
URL="https://dns.cn-east-3.myhuaweicloud.com/v2"
repx = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
IP =""
# 只要是可以直接返回ip地址的可以多添加几个
urls=["https://whatismyip.akamai.com","https://checkip.amazonaws.com"]
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地址
    for url in urls:
        IP=requests.get(url).text.strip()
        if repx.match(IP):
            break
    # 如果是ipv4地址
    if repx.match(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()
        
   
下载:ip4.py