ubuntu debian阿里云域名动态解析DDNS脚本

#!/bin/bash
#安装依赖 apt-get install dnsutils curl openssl
#dnstiils是为了用nslookup命令查询dns记录。dig命令也行,需要改代码
#curl是用来和阿里DDNS交互
#openssl用来加密


ali_id="Access Key ID"  #阿里云akid
ali_key="Access Key Secret"     #阿里云aks
ali_name1='子域名'
ali_domain='主域名'
ali_ttl="600"
eths='指定网卡,为空默认有公网ipv6的网卡'
dns_server="47.118.199.199"     #这是域名解析dns,我的是 dns25.hichina.com。自行指定,可以注释或者为空。建议查找自己域名所属dns,可以快速确定是否被登记记录。用其他DNS服务器缓存较慢,导致脚本连续发起登记请求。

if [ "$ali_name1" = "@" ]
then
ali_name=$ali_domain
else
ali_name=$ali_name1.$ali_domain
fi

now=`date`

ipv6=`ip -6 addr show $eths | grep "inet6.*global" | awk '{print $2}' | awk -F"/" '{print $1}' | sed -n 1p`

current_ipv6=`nslookup -q=AAAA $ali_name $dns_server | grep 'Address: ' | tail -n1 | awk '{print $NF}'`

timestamp=`date -u "+%Y-%m-%dT%H%%3A%M%%3A%SZ"`

urlencode() {
# urlencode 
out=""
while read -n1 c
do
case $c in
[a-zA-Z0-9._-]) out="$out$c" ;;
*) out="$out`printf '%%%02X' "'$c"`" ;;
esac
done
echo -n $out
}

enc() {
echo -n "$1" | urlencode
}

send_request() {
local args="AccessKeyId=$ali_id&Action=$1&Format=json&$2&Version=2015-01-09"
local hash=$(echo -n "GET&%2F&$(enc "$args")" | openssl dgst -sha1 -hmac "$ali_key&" -binary | openssl base64)
curl -s "https://alidns.aliyuncs.com/?$args&Signature=$(enc "$hash")"
}

get_recordid() {
grep -Eo '"RecordId":"[0-9]+"' | cut -d':' -f2 | tr -d '"'
}

query_recordid() {
send_request "DescribeSubDomainRecords" "SignatureMethod=HMAC-SHA1&SignatureNonce=$timestamp&SignatureVersion=1.0&SubDomain=$ali_name&Timestamp=$timestamp&Type=AAAA"
}

update_record() {
send_request "UpdateDomainRecord" "RR=$ali_name1&RecordId=$1&SignatureMethod=HMAC-SHA1&SignatureNonce=$timestamp&SignatureVersion=1.0&TTL=$ali_ttl&Timestamp=$timestamp&Type=AAAA&Value=$(enc $ipv6)"
}

add_record() {
send_request "AddDomainRecord&DomainName=$ali_domain" "RR=$ali_name1&SignatureMethod=HMAC-SHA1&SignatureNonce=$timestamp&SignatureVersion=1.0&TTL=$ali_ttl&Timestamp=$timestamp&Type=AAAA&Value=$(enc $ipv6)"
}

###############################################
echo -e "当前记录: $current_ipv6 >>> $ali_name"

if [[ $ipv6 != "" ]]; then
if [[ $ipv6 != $current_ipv6 ]]; then
if [[ "$current_ipv6" = "" ]] ;then
ali_record_id=`add_record | get_recordid`
echo -e "添加新记录: ${ipv6} >>> $ali_name"
else
ali_record_id=`query_recordid|get_recordid`
update_record $ali_record_id >/dev/null
echo -e "更新记录: ${ipv6} >>> $ali_name "
fi
else
echo -e "无需更新: $current_ipv6 >>> $ali_name"
fi
else
        echo "未取得IPV6"
fi

非原创,参考本站的一个大佬的代码后魔改的。

本来想贴个原创链接的,翻来翻去没找到。如原作者看到请联系我删除或者加链接。

你可能感兴趣的:(服务器,linux,运维)