代替DDNS方案,自动更新CloudFlare的AAAA记录

为解决DDNS更新慢的问题,直接通过cloudflare的API来更新AAAA记录

将下面代码保存成cloudflare_ipv6_update.ps1

$config = @{}
$config.zone_id = "11111111" #填写CF域名编号
$config.auth_email = "[email protected]" #填写CF账号
$config.auth_key = "11111111" #填写CF密钥
$config.delay = 10
[System.Net.ServicePointManager]::SecurityProtocol=[System.Net.SecurityProtocolType]::Tls12
$dot=@{}
$dot.linemax = 120
$dot.current = 0
Function PrintDot(){
    $char = "."
    $dot.current++
    if ($dot.current -eq 1) {
        $text = ([String](Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) + " "
        Write-Host -NoNewline $text
    }
    if ($dot.current -ge $dot.linemax) {
        $dot.current = 0
        Write-Host $char
    } else {
        Write-Host -NoNewline $char
    }
}
Function PrintError($text) {
    Write-Host
    Write-Host -NoNewline ([String](Get-Date -Format 'yyyy-MM-dd HH:mm:ss')) $text
}
while (1) {
    $Uri = "http://ipv6.lookup.test-ipv6.com/ip/"
    $ret = (Invoke-WebRequest -Uri $Uri)
    if ($ret.StatusCode -ne 200) {
        PrintError "IP获取失败,延迟 $($config.delay) 秒"
        Start-Sleep -Seconds $config.delay
        continue
    }
    $lookup_ipv6 = ConvertFrom-Json $ret.Content
    $parttern="^([a-f0-9]{1,4}(:[a-f0-9]{1,4}){7}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){0,7}::[a-f0-9]{0,4}(:[a-f0-9]{1,4}){0,7})$"
    if ($lookup_ipv6.ip -inotmatch $parttern) {
        PrintError "获取的IP格式错误,延迟 $($config.delay) 秒"
        $lookup_ipv6
        Start-Sleep -Seconds $config.delay
        continue
    }
    $Uri = "https://api.cloudflare.com/client/v4/zones/" + $config.zone_id + "/dns_records?type=AAAA"
    $Headers = @{}
    $Headers."Content-Type" = "application/json"
    $Headers."X-Auth-Email" = $config.auth_email
    $Headers."X-Auth-Key" = $config.auth_key
    $ret = (Invoke-WebRequest -Uri $Uri -Headers $Headers)
    if ($ret.StatusCode -ne 200) {
        PrintError "域名记录获取失败,延迟 $($config.delay) 秒"
        Start-Sleep -Seconds $config.delay
        continue
    }
    $dns_record_1 = ConvertFrom-Json $ret.Content
    $ret = @{}
    if ($dns_record_1.result.content -eq $lookup_ipv6.ip) {
        PrintDot
        Start-Sleep -Seconds $config.delay
        continue
    }
    $Uri = "https://api.cloudflare.com/client/v4/zones/" + $config.zone_id + "/dns_records/" + $dns_record_1.result.id
    $Json = @{}
    $Json.type = $dns_record_1.result.type
    $Json.name = $dns_record_1.result.name
    $Json.content = $lookup_ipv6.ip
    $Json.proxied = [Bool]1
    $Body = ConvertTo-Json $Json
    $Body
    $ret = (Invoke-WebRequest -Method Put -Uri $Uri -Headers $Headers -Body $Body)
    Start-Sleep -Seconds $config.delay
}

 

你可能感兴趣的:(代替DDNS方案,自动更新CloudFlare的AAAA记录)