keyword:阿里云域名动态解析dns,ddns,不固定ip动态解析,自动域名解析,域名解析到动态ip
电信宽带,打电话给来了公网ip但是不固定,内网服务器没有固定的公网IP,每隔两三天会变一次,手工修改太麻烦,故而想到使用阿里云的接口动态修改,代码使用PHP实现
1访问外网接口获取到服务器出口真实IP
2.调用阿里云解析DescribeSubDomainRecords接口获取到域名的RecordId
3.使用UpdateDomainRecord修改记录值
4.加入到定时任务,每隔一段时间执行下即可
阿里云sdk composer引入
composer require alibabacloud/sdk
ddns.php
<?php require './vendor/autoload.php'; use AlibabaCloud\Client\AlibabaCloud; use AlibabaCloud\Client\Exception\ClientException; use AlibabaCloud\Client\Exception\ServerException; $isLocalIP = true; // 本地远程地址true,请求地址false $accessKeyId = ''; // 你的accessKeyId 申请地址https://usercenter.console.aliyun.com/#/manage/ak $accessSecret = ''; // 你的accessSecret $domains = ['xxx.xxx.com']; //域名列表,支持子域名 $getIpUrl = 'http://ifconfig.me/ip';//获取出口IP接口地址 if ($isLocalIP) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $getIpUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $data = curl_exec($ch); curl_close($ch); $ip = $data; } else { $ip = $_SERVER['REMOTE_ADDR']; } try { //没有改动则不更新 if ($ip == file_get_contents('./ip')) return 0; else file_put_contents('./ip', $ip); AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret) ->regionId('cn-hangzhou')// replace regionId as you need ->asDefaultClient(); $request = AlibabaCloud::rpc() ->product('Alidns') ->scheme('http') ->version('2015-01-09') ->action('DescribeSubDomainRecords') ->method('POST') ->host('alidns.aliyuncs.com'); foreach ($domains as $domain) { $requestClone = clone $request; $result = $requestClone->options([ 'query' => [ 'RegionId' => "default", 'SubDomain' => $domain, ], ])->request(); $domainInfo = $result->toArray(); if (empty($domainInfo['DomainRecords']['Record'])) { return; } $records = $domainInfo['DomainRecords']['Record']; foreach ($records as $record) { if ($record['Type'] == 'A') { $recordId = $record['RecordId']; $domainArr = explode('.', $domain); $res = AlibabaCloud::rpc() ->product('Alidns') ->scheme('http') ->version('2015-01-09') ->action('UpdateDomainRecord') ->method('POST') ->host('alidns.aliyuncs.com') ->options([ 'query' => [ 'RegionId' => "default", 'RecordId' => $recordId, 'RR' => $domainArr[0], 'Type' => "A", 'Value' => $ip, ], ]) ->request(); file_put_contents('./log.txt', json_encode($res) . PHP_EOL, FILE_APPEND); } } } } catch (ClientException $e) { echo $e->getErrorMessage() . PHP_EOL; file_put_contents('./log.txt', $e->getErrorMessage() . PHP_EOL, FILE_APPEND); } catch (ServerException $e) { echo $e->getErrorMessage() . PHP_EOL; file_put_contents('./log.txt', $e->getErrorMessage() . PHP_EOL, FILE_APPEND); } catch (\Throwable $e){ echo $e->getErrorMessage() . PHP_EOL; file_put_contents('./log.txt', $e->getErrorMessage() . PHP_EOL, FILE_APPEND);
将下面命令加到 定时任务里(宝塔,corntab等等)
php start.php
原文链接:https://blog.csdn.net/flysnownet/article/details/112137840
© 版权声明
声明📢本站内容均来自互联网,归原创作者所有,如有侵权必删除。
本站文章皆由CC-4.0协议发布,如无来源则为原创,转载请注明出处。
THE END