Skip to content

Instantly share code, notes, and snippets.

@houming818
Last active March 20, 2019 11:36
Show Gist options
  • Save houming818/826431ed14111488be95d7260ee7080d to your computer and use it in GitHub Desktop.
Save houming818/826431ed14111488be95d7260ee7080d to your computer and use it in GitHub Desktop.
auto update the public IP for the record in dnspod. 自动更新dnspod解析记录的脚本
#!/bin/sh
# HOST STATUS
hostname=""
public_ip=""
# RECORD STATUS
code=""
value=""
message=""
record_id=""
# CONFIG
LOGIN_TOKEN=""
DOMAIN_ID=""
setHostname() {
hostname=$(hostname -s)
echo 'HOST STATUS: hostname='$hostname
}
setPublicIp() {
public_ip=$(curl -s http://ns1.dnspod.net:6666)
echo 'HOST STATUS: public_ip='$public_ip
}
createRecord(){
echo 'RECORD STATUS: create '"$hostname"'.grepcode.cn'
ret=$(curl -sX POST https://dnsapi.cn/Record.Create -d "login_token="$LOGIN_TOKEN"&format=json&domain_id="$DOMAIN_ID"&sub_domain="$hostname"&record_line_id=0&record_type=A&value="$public_ip)
code=$(echo $ret|perl -pe 's/.*(?<="code":")(\d+).*/\1/g')
message=$(echo $ret|perl -pe 's/.*(?<="message":")([\w ]*).*/\1/g')
if [ "$code" -eq 1 ];
then
echo "RECORD STATUS: create succ, "$message
else
echo "RECORD STATUS: create fail, "$message
fi
}
updateRecord(){
echo 'UPDATE RECORD: start'
ret=$(curl -sX POST https://dnsapi.cn/Record.Modify -d "login_token="$LOGIN_TOKEN"&format=json&domain_id="$DOMAIN_ID"&sub_domain="$hostname"&record_id="$record_id"&record_line_id=0&record_type=A&value="$public_ip)
code=$(echo $ret|perl -pe 's/.*(?<="code":")(\d+).*/\1/g')
message=$(echo $ret|perl -pe 's/.*(?<="message":")([\w ]*).*/\1/g')
if [ "$code" -eq 1 ];
then
echo "RECORD STATUS: update succ, "$message
return 0
else
echo "RECORD STATUS: update fail, "$message
return $code
fi
}
keepRecord() {
echo "RECORD STATUS: init"
record=$(curl -sX POST https://dnsapi.cn/Record.List -d "login_token="$LOGIN_TOKEN"&domain_id="$DOMAIN_ID"&sub_domain="$hostname"&format=json")
code=$(echo $record|perl -pe 's/.*(?<="code":")(\d+).*/\1/g')
message=$(echo $record|perl -pe 's/.*(?<="message":")([\w ]*).*/\1/g')
if [ "$code" -eq 10 ];
then
echo "RECORD STATUS: init fail, "$message
createRecord
elif [ "$code" -eq 1 ]
then
echo "RECORD STATUS: init succ, "$message
value=$(echo $record|perl -pe 's/.*(?<="value":")([\w|.]*).*/\1/g')
record_id=$(echo $record|perl -pe 's/.*(?<="id":")(\d+).*/\1/g')
echo $record_id
echo "RECORD STATUS: host="$hostname'.grepcode.cn'
echo "RECORD STATUS: value="$value
if [ "$value" != "$public_ip" ];
then
echo "RECORD STATUS: DIRTY"
updateRecord
else
echo "RECORD STATUS: OK"
return 0
fi
else
echo 'Unknown code: '$code
echo 'Error message: '$message
fi
}
setHostname
setPublicIp
keepRecord
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment