125 lines
2.6 KiB
Go
125 lines
2.6 KiB
Go
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"log"
|
||
"net"
|
||
"os"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
|
||
)
|
||
|
||
func main() {
|
||
domain := os.Getenv("DOMAIN")
|
||
rr := os.Getenv("RR")
|
||
regionID := os.Getenv("REGIONID")
|
||
if regionID == "" {
|
||
regionID = "cn-hangzhou"
|
||
}
|
||
accessKeyID := os.Getenv("ACCESSKEYID")
|
||
accessSecret := os.Getenv("ACCESSSECRET")
|
||
|
||
ip6 := ""
|
||
for {
|
||
time.Sleep(10 * time.Second)
|
||
|
||
addrs, err := net.InterfaceAddrs()
|
||
if err != nil {
|
||
log.Println(err)
|
||
continue
|
||
}
|
||
|
||
currentIPV6 := ""
|
||
for _, address := range addrs {
|
||
// 检查 ip 地址判断是否回环地址
|
||
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && !ipnet.IP.IsPrivate() && ipnet.IP.IsGlobalUnicast() {
|
||
if ipnet.IP.To16() != nil {
|
||
if currentIPV6 != ipnet.IP.String() {
|
||
currentIPV6 = ipnet.IP.String()
|
||
break
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if currentIPV6 == "" || currentIPV6 == ip6 {
|
||
continue
|
||
}
|
||
|
||
client, err := alidns.NewClientWithAccessKey(regionID, accessKeyID, accessSecret)
|
||
if err != nil {
|
||
log.Println(err.Error())
|
||
continue
|
||
}
|
||
|
||
drRequest := alidns.CreateDescribeDomainRecordsRequest()
|
||
drRequest.KeyWord = rr
|
||
drRequest.DomainName = domain
|
||
drRequest.TypeKeyWord = "AAAA"
|
||
|
||
drResponse, err := client.DescribeDomainRecords(drRequest)
|
||
if err != nil {
|
||
log.Println(err)
|
||
continue
|
||
}
|
||
if !drResponse.IsSuccess() {
|
||
continue
|
||
}
|
||
|
||
rid := ""
|
||
for _, r := range drResponse.DomainRecords.Record {
|
||
rid = r.RecordId
|
||
if r.Value == currentIPV6 {
|
||
ip6 = currentIPV6
|
||
rid = ""
|
||
}
|
||
break
|
||
}
|
||
|
||
if rid == "" {
|
||
continue
|
||
}
|
||
|
||
//修改域名对应的IP,修改成功后continue
|
||
req := alidns.CreateUpdateDomainRecordRequest()
|
||
req.Scheme = "https"
|
||
req.RR = rr
|
||
req.RecordId = rid
|
||
req.Value = currentIPV6
|
||
req.Type = "AAAA"
|
||
|
||
resp, err := client.UpdateDomainRecord(req)
|
||
if err != nil {
|
||
log.Println(err.Error())
|
||
if !strings.Contains(err.Error(), fmt.Sprintf("not %s", domain)) {
|
||
continue
|
||
}
|
||
}
|
||
|
||
if resp.IsSuccess() {
|
||
ip6 = currentIPV6
|
||
log.Println("update success: ", ip6)
|
||
continue
|
||
}
|
||
|
||
//当域名修改失败时判断是否是没有对应的记录,不存在时创建新的域名记录
|
||
request := alidns.CreateAddDomainRecordRequest()
|
||
request.Scheme = "https"
|
||
request.Value = currentIPV6
|
||
request.Type = "AAAA"
|
||
request.RR = rr
|
||
request.DomainName = domain
|
||
response, err := client.AddDomainRecord(request)
|
||
if err != nil {
|
||
fmt.Print(err.Error())
|
||
continue
|
||
}
|
||
if !response.IsSuccess() {
|
||
fmt.Print(response.GetHttpContentString())
|
||
ip6 = currentIPV6
|
||
}
|
||
}
|
||
}
|