keyword:阿里云域名动态解析dns,ddns,不固定ip动态解析,自动域名解析,域名解析到动态ip
前言
电信宽带,打电话给来了公网ip但是不固定,内网服务器没有固定的公网IP,每隔两三天会变一次,手工修改太麻烦,故而想到使用阿里云的接口动态修改,代码使用PHP实现
流程
1访问外网接口获取到服务器出口真实IP
如What Is My IP Address? - ifconfig.me
2.调用阿里云解析DescribeSubDomainRecords接口获取到域名的RecordId
3.使用UpdateDomainRecord修改记录值
4.加入到定时任务,每隔一段时间执行下即可
代码
阿里云sdk composer引入
composer require alibabacloud/sdk
ddns.php
<?phprequire './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./#/manage/ak$accessSecret = ''; // 你的accessSecret$domains = ['']; //域名列表,支持子域名$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;elsefile_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('-01-09')->action('DescribeSubDomainRecords')->method('POST')->host('');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('-01-09')->action('UpdateDomainRecord')->method('POST')->host('')->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