利用阿里云域名搭建内网服务器(内网穿透)

在搭建内网非固定 IP 的 web 服务器时,在外网访问时会因为ip不断变化了,而导致访问失败,虽然有很多这种动态解析软件,但使用效果,速度都有一定的现在,还有一些是收费的,我们可以利用阿里云的域名 api,不断的更新域名解析地址,来达到动态解析的效果。

首先我们阿里云上添加一条解析记录,然后在内网服务器上创建定时任务,每隔一段时间访问自己的程序代码,进行设置域名的解析记录

<?php
date_default_timezone_set('UTC');
include_once 'alicloud-php-updaterecord/V20150109/AlicloudUpdateRecord.php';
use Roura\Alicloud\V20150109\AlicloudUpdateRecord;
$AccessKeyId     = 'ACCESS_KEY_ID';   //阿里云api
$AccessKeySecret = 'ACCESS_KEY_SECRET';//阿里云api
$updater         = new AlicloudUpdateRecord($AccessKeyId, $AccessKeySecret);
$newIp = $_SERVER['REMOTE_ADDR']; // New IP
$updater->setDomainName('DOMAIN.COM');//自己的域名
$updater->setRecordType('A');//记录类型
$updater->setRR('@');//主机记录
$updater->setValue($newIp);//设置新的ip
print_r($updater->sendRequest());

alicloud-php-updaterecord/V20150109/AlicloudUpdateRecord.php 文件内容

<?php
namespace Roura\Alicloud\V20150109;
use \Exception;
class AlicloudUpdateRecord{
    public $domainName;
    public $rR;
    public $type;
    public $value;
    public $accessKeyId;
    public $accessKeySecret;
    function __construct(string $accessKeyId,string $accessKeySecret) {
        $this->accessKeyId     = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
    }    
    public function getSignature(string $CanonicalQueryString): string{
        $HTTPMethod                  = 'GET';
        $slash                       = urlencode('/');
        $EncodedCanonicalQueryString = urlencode($CanonicalQueryString);
        $StringToSign                = "{$HTTPMethod}&{$slash}&{$EncodedCanonicalQueryString}";
        $StringToSign                = str_replace('%40', '%2540', $StringToSign);
        $HMAC                        = hash_hmac('sha1', $StringToSign, "{$this->accessKeySecret}&", true);
        return base64_encode($HMAC);
    }

    public function getDate(): string{
        $timestamp = date('U');
        $date      = date('Y-m-d', $timestamp);
        $H         = date('H', $timestamp);
        $i         = date('i', $timestamp);
        $s         = date('s', $timestamp);
        return "{$date}T{$H}%3A{$i}%3A{$s}";
    }

    public function getRecordId(): string{
        $queries = [
            'AccessKeyId' => $this->accessKeyId,
            'Action' => 'DescribeDomainRecords',
            'DomainName' => $this->domainName,
            'Format' => 'json',
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => random_int(1000000000, 9999999999),
            'SignatureVersion' => '1.0',
            'Timestamp' => $this->getDate(),
            'Version' => '2015-01-09'
        ];
        $response = $this->doRequest($queries);		
        $recordList = $response['DomainRecords']['Record'];
        $RR = null;
        foreach ($recordList as $key => $record) {
            if ($this->rR === $record['RR']) {
                $RR = $record;
            }
        }
        if ($RR === null) {
            die('RR ' . $this->rR . ' not found.');
        }
        return $RR['RecordId'];
    }

    public function setDomainName(string $domainName){
        $this->domainName = $domainName;
    }
    
    public function setValue(string $value){
        $this->value = $value;
    }
    
    public function setRR(string $rR){
        $this->rR = $rR;
    }
  
    public function setRecordId(string $recordId){
        $this->recordId = $recordId;
    }
    public function setRecordType(string $type){
        $this->type = $type;
    }
    public function doRequest(Array $queries): array{
        $CanonicalQueryString = '';
        $i                    = 0;
        foreach ($queries as $param => $query) {
            $CanonicalQueryString .= $i === 0 ? null : '&';
            $CanonicalQueryString .= "{$param}={$query}";
            $i++;
        }
        $signature  = $this->getSignature($CanonicalQueryString);
        $requestUrl = "http://dns.aliyuncs.com/?{$CanonicalQueryString}&Signature=" . urlencode($signature);
        $response   = file_get_contents($requestUrl, false, stream_context_create([
            'http' => [
                'ignore_errors' => true
            ]
        ]));
        return json_decode($response, true);
    }    
    public function sendRequest(): array{
        $queries = [
            'AccessKeyId' => $this->accessKeyId,
            'Action' => 'UpdateDomainRecord',
            'Format' => 'json',
            'RR' => $this->rR,
            'RecordId' => $this->getRecordId(),
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => random_int(1000000000, 9999999999),
            'SignatureVersion' => '1.0',
            'Timestamp' => $this->getDate(),
            'Type' => $this->type,
            'Value' => $this->value,
            'Version' => '2015-01-09'
        ];
        return $this->doRequest($queries);
    }
}

本文收集于网络,仅供技术交流使用,本站不拥有所有权,不承担相关法律责任。如果发现本站有涉嫌抄袭的内容, 欢迎发送邮件至 admin@webse.cn 举报,一经查实,本站将立刻删除涉嫌侵权内容,本文链接:https://webse.cn/7785.html

发表评论

登录后才能评论