Exemplo n.º 1
0
        public List <DescribeDomainRecords_Record> GetRecords(DescribeDomains_Domain domain)
        {
            var req = new DescribeDomainRecordsRequest();

            req.DomainName = domain.DomainName;
            return(getResponse(req).DomainRecords);
        }
Exemplo n.º 2
0
 /// <summary>
 /// 根据域名获取解析记录
 /// </summary>
 /// <param name="domain">域名</param>
 /// <returns></returns>
 public static List <DescribeDomainRecordsResponse.Record> GetDomainRecords(string domain)
 {
     try
     {
         IClientProfile               clientProfile = DefaultProfile.GetProfile("cn-hangzhou", CGlobalConfig.AccessKey, CGlobalConfig.AccessKeySecret);
         DefaultAcsClient             client        = new DefaultAcsClient(clientProfile);
         DescribeDomainRecordsRequest request       = new DescribeDomainRecordsRequest();
         request.DomainName = domain;
         try
         {
             DescribeDomainRecordsResponse response           = client.GetAcsResponse(request);
             List <DescribeDomainRecordsResponse.Record> list = response.DomainRecords;
             return(list);
         }
         catch (ServerException e)
         {
             CLogHelper.WriteError(" GetDomainRecords 发送异常:" + e.ErrorCode + "\t" + e.ErrorMessage);
         }
         catch (ClientException e)
         {
             CLogHelper.WriteError(" GetDomainRecords 发送异常:" + e.ErrorCode + "\t" + e.ErrorMessage);
         }
     }
     catch (Exception ex)
     {
         CLogHelper.WriteError(" GetDomainRecords 发送异常:" + ex.ToString());
     }
     return(new List <DescribeDomainRecordsResponse.Record>());
 }
Exemplo n.º 3
0
        public IEnumerable <DescribeRecord> GetRecords(string domainName)
        {
            IClientProfile   profile = DefaultProfile.GetProfile("cn-hangzhou", accessKey, accessSecret);
            DefaultAcsClient client  = new DefaultAcsClient(profile);

            var request = new DescribeDomainRecordsRequest();

            request.DomainName  = domainName;
            request.TypeKeyWord = "A";

            var response = client.GetAcsResponse(request);

            if (response.TotalCount == 0)
            {
                throw new Exception("请先手动解析几条A记录");
            }

            return(response.DomainRecords.Select(x => new DescribeRecord()
            {
                RecordId = x.RecordId,
                Value = x.Value,
                RR = x.RR,
                Type = x.Type,
            }));
        }
Exemplo n.º 4
0
        public Task Execute(IJobExecutionContext context)
        {
            var publicIP = GetPublicIPEx();
            var cachedIP = CacheHelper.GetCacheValue <string>(CACHEKEY_CachedIP);

            if (!string.IsNullOrWhiteSpace(cachedIP) && cachedIP.Equals(publicIP, StringComparison.OrdinalIgnoreCase))
            {
                return(Task.CompletedTask);
            }

            IClientProfile   profile = DefaultProfile.GetProfile("cn-hangzhou", ConfigUtil.GetConfigVariableValue("accessKeyId"), ConfigUtil.GetConfigVariableValue("accessSecret"));
            DefaultAcsClient client  = new DefaultAcsClient(profile);
            var request = new DescribeDomainRecordsRequest();

            //request.Value = "3.0.3.0";
            //request.Type = "A";
            //request.RR = "apitest1";
            request.DomainName  = ConfigUtil.GetConfigVariableValue("DomainName");
            request.TypeKeyWord = ConfigUtil.GetConfigVariableValue("DomainRecordType");
            request.RRKeyWord   = ConfigUtil.GetConfigVariableValue("DomainRecordRR");
            try
            {
                var response = client.GetAcsResponse(request);
                if (response.TotalCount > 0)
                {
                    var rec = response.DomainRecords.FirstOrDefault(t => t.RR.Equals(request.RRKeyWord, StringComparison.CurrentCultureIgnoreCase));
                    if (rec != null && rec.Value != publicIP)
                    {
                        var reqChange = new UpdateDomainRecordRequest();
                        reqChange.RecordId = rec.RecordId;
                        reqChange.RR       = rec.RR;
                        reqChange.Type     = rec.Type;
                        reqChange.Value    = publicIP;

                        var respChange = client.GetAcsResponse(reqChange);

                        CacheHelper.SetCacheValue(CACHEKEY_CachedIP, publicIP);

                        Console.WriteLine($"[{DateTime.Now}]:{rec.RR}.{rec.DomainName} Changed to IP {publicIP} success");
                    }
                }
                // Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                Console.WriteLine($"[{DateTime.Now}]【Exception】{e}");
            }
            catch (ClientException e)
            {
                Console.WriteLine($"[{DateTime.Now}]【Exception】{e}");
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 5
0
        private void Init()
        {
            var profile = DefaultProfile.GetProfile(Options.RegionId, Options.AccessKeyId, Options.AccessKeySecret);

            client  = new DefaultAcsClient(profile);
            request = new DescribeDomainRecordsRequest();

            //request.Url = "http://domain.aliyuncs.com/";
            request.DomainName  = Options.DomainName;
            request.TypeKeyWord = Options.DomainType;
            //request.ActionName = "DescribeDomainRecords";
        }
Exemplo n.º 6
0
        /// <summary>
        /// 获取当前的解析值
        /// </summary>
        /// <returns></returns>
        public Record DescribeDomains()
        {
            var req = new DescribeDomainRecordsRequest()
            {
                DomainName = CGlobalConfig.DomainName
            };
            var response = aliyunClient.Execute(req);

            var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == CGlobalConfig.FirstName && rec.Type == "A");

            return(updateRecord);
        }
Exemplo n.º 7
0
        //public DNSApi(string accessKeyId, string accessSecret, string regionId, string domainName,) : this(accessKeyId, accessSecret, domainName, regionId)
        //{
        //    this.regionId = regionId;
        //}

        /// <summary>
        /// 获取解析记录列表
        /// </summary>
        /// <param name="domainName"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public DescribeDomainRecordsResponse GetDomainRecords(string domainName, long pageNumber, long pageSize = 20)
        {
            profile       = DefaultProfile.GetProfile(regionId, accessKeyId, accessSecret);
            defaultClient = new DefaultAcsClient(profile);

            var request = new DescribeDomainRecordsRequest();

            request.DomainName = domainName;
            request.PageNumber = pageNumber;
            request.PageSize   = pageSize;
            var response = defaultClient.GetAcsResponse(request);

            return(response);
        }
Exemplo n.º 8
0
        public static void DomainRecordCheck(DefaultAcsClient client, string checkDomain, string currentIP)
        {
            try
            {
                DescribeDomainRecordsRequest req = new DescribeDomainRecordsRequest();
                req.PageSize   = 10;
                req.PageNumber = 1;
                req.DomainName = checkDomain;
                var rsp = client.GetAcsResponse <DescribeDomainRecordsResponse>(req);

                // 修改
                foreach (var record in rsp.DomainRecords)
                {
                    if (record.Value == currentIP)
                    {
                        continue;
                    }

                    Console.WriteLine($"域名: {checkDomain} 当前解析地址为 {record.Value}, 需要重新解析成 {currentIP}, RR: {record.RR}, Type: {record.Type}");

                    UpdateDomainRecordRequest updateReq = new UpdateDomainRecordRequest();
                    updateReq.RecordId = record.RecordId;
                    updateReq.RR       = record.RR;
                    updateReq.Type     = record.Type;
                    updateReq.Value    = currentIP;

                    try
                    {
                        var updateRsp = client.GetAcsResponse <UpdateDomainRecordResponse>(updateReq);
                        if (updateRsp.HttpResponse.isSuccess())
                        {
                            Console.WriteLine("解析地址修改成功!");
                        }
                        else
                        {
                            Console.WriteLine("解析地址修改失败! -- " + Encoding.UTF8.GetString(updateRsp.HttpResponse.Content));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("请求修改解析地址出现异常: " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("DomainRecordCheck出现异常: ", ex.Message);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 获取记录列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public OutAliyunDNSVO DescribeDomainRecords(InAliyunDNSVO info)
        {
            IClientProfile   profile = DefaultProfile.GetProfile("cn-hangzhou", info.accessKeyId, info.accessSecret);
            DefaultAcsClient client  = new DefaultAcsClient(profile);
            var request = new DescribeDomainRecordsRequest()
            {
                DomainName = info.DomainName,
                KeyWord    = info.KeyWord,
                SearchMode = "EXACT",
                Type       = "A"
            };
            var response = client.GetAcsResponse(request);

            return(JsonConvert.DeserializeObject <OutAliyunDNSVO>(Encoding.Default.GetString(response.HttpResponse.Content)));
        }
Exemplo n.º 10
0
        public DomainRecord(DomainRecordOptions options)
        {
            Options = options;
            var profile = DefaultProfile.GetProfile(Options.RegionId, Options.AccessKeyId, Options.AccessKeySecret);

            client  = new DefaultAcsClient(profile);
            request = new DescribeDomainRecordsRequest();

            //request.Url = "http://domain.aliyuncs.com/";
            request.DomainName  = Options.DomainName;
            request.TypeKeyWord = Options.DomainType;
            //request.ActionName = "DescribeDomainRecords";

            var response = client.GetAcsResponse(request);

            describeDomainRecords_Records = response.DomainRecords;
        }
Exemplo n.º 11
0
        /// <summary>
        /// 获取某域名的解析记录列表
        /// </summary>
        /// <param name="Domain"></param>
        /// <returns></returns>
        public List <DescribeDomainRecordsResponse.Record> GetDomainRecords(string Domain)
        {
            var request = new DescribeDomainRecordsRequest()
            {
                DomainName = Domain,
                PageNumber = 1,
                PageSize   = 500
            };

            try
            {
                var response = client.GetAcsResponse(request);
                return(response.DomainRecords);
            }
            catch
            {
                return(new List <DescribeDomainRecordsResponse.Record>());
            }
        }
        private DescribeDomainRecords_Record GetCurrentConfiguration(string domain, string host)
        {
            DescribeDomainRecords_Record x = null;

            try
            {
                var request = new DescribeDomainRecordsRequest();
                request.DomainName = domain;
                DefaultAcsClient.DoAction(request, ClientProfile);
                var response3 = DefaultAcsClient.GetAcsResponse(request);
                x = response3.DomainRecords.SingleOrDefault(d1 => d1.RR == host);
                return(x);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
            throw new Exception("Unknown exception");
        }
Exemplo n.º 13
0
        public void SetupRecord(string domain, string rrKeyword, string newValue)
        {
            var reqRecords = new DescribeDomainRecordsRequest();

            reqRecords.DomainName = domain;
            reqRecords.RRKeyWord  = rrKeyword;
            reqRecords.Type       = "A";
            var records = getResponse(reqRecords).DomainRecords;

            if (records.Count == 0)
            {
                var add = new AddDomainRecordRequest
                {
                    RR         = rrKeyword,
                    _Value     = newValue,
                    Type       = "A",
                    TTL        = TTL,
                    DomainName = domain
                };
                getResponse(add);
                return;
            }

            var record = records[0];

            if (newValue == record._Value &&
                record.RR == rrKeyword &&
                record.Type == "A" &&
                record.TTL == TTL)   //解析值没有变化则跳出
            {
                return;
            }

            var reqUpdate = new UpdateDomainRecordRequest();

            reqUpdate.RR       = rrKeyword;
            reqUpdate.RecordId = record.RecordId;
            reqUpdate._Value   = newValue;
            reqUpdate.Type     = "A";
            reqUpdate.TTL      = TTL;
            getResponse(reqUpdate);
        }
Exemplo n.º 14
0
        // 获取阿里云域名解析记录
        private static Record GetDomainRecord()
        {
            int    errorTimes = 0;
            string errMessage;

            while (true)
            {
                var aliyunClient = new DefaultAliyunClient(HOST_URL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
                var req          = new DescribeDomainRecordsRequest()
                {
                    DomainName = DOMAIN_NAME
                };
                try
                {
                    var    response = aliyunClient.Execute(req);
                    Record record   = response.DomainRecords.FirstOrDefault(rec => rec.RR == SUBDOMAIN_NAME && rec.Type == "A");
                    if (record != null && !string.IsNullOrWhiteSpace(record.Value))
                    {
                        LogHelper.WriteLog("获取阿里云域名解析记录为:" + record.Value);
                        return(record);
                    }
                    errMessage = "域名解析查询结果为空(可能密钥错误),正在尝试重新获取";
                }
                catch
                {
                    errMessage = "网络连接错误,未能请求到阿里云域名解析服务,正在尝试重新连接";
                }
                errorTimes++;
                if (errorTimes > ERROR_RETRIES)
                {
                    LogHelper.WriteLog("多次请求阿里云域名解析服务失败,程序退出");
                    Environment.Exit(0);
                }
                else
                {
                    LogHelper.WriteLog(errMessage);
                }
                Thread.Sleep(TIME_UNIT);
            }
        }
Exemplo n.º 15
0
        private (string recordId, string currentIP) GetDNSRecord()
        {
            var recordsRequest = new DescribeDomainRecordsRequest
            {
                DomainName = _domainName,
                RRKeyWord  = _rr
            };
            var recordResponse     = _acsClient.GetAcsResponse(recordsRequest);
            var recordStringResult = Encoding.Default.GetString(recordResponse.HttpResponse.Content);
            var recordJsonResult   = JsonConvert.DeserializeObject <JObject>(recordStringResult);

            if (recordJsonResult["TotalCount"].Value <int>() == 0)
            {
                return(null, null);
            }
            else
            {
                var recordId  = recordJsonResult["DomainRecords"]["Record"][0]["RecordId"].ToString();
                var currentIP = recordJsonResult["DomainRecords"]["Record"][0]["Value"].ToString();
                return(recordId, currentIP);
            }
        }
Exemplo n.º 16
0
        //定时执行事件
        private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            //每次都重新获取配置(可以动态修改而不用重启服务)
            GetConfig();
            if (!configExist_)
            {
                logger.Error(" Not Config Yet ...... 【Skip】");
                return;
            }
            string currentInternetIp = GetInternetIP();

            if (currentInternetIp.Length == 0)
            {
                logger.Info("Can't Get Current Internet Ip ...... 【Skip】");
                return;
            }
            IClientProfile               clientProfile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId_, accessKeySecret_);
            DefaultAcsClient             client        = new DefaultAcsClient();
            DescribeDomainRecordsRequest reqFetch      = new DescribeDomainRecordsRequest();

            reqFetch.AcceptFormat = Aliyun.Acs.Core.Http.FormatType.JSON;
            reqFetch.DomainName   = domainName_;

            string dnsIp = "", recordId = "";

            try {
                DescribeDomainRecordsResponse resFetch = client.GetAcsResponse(reqFetch);
                foreach (var r in resFetch.DomainRecords)
                {
                    if (r.RR == subDomainName_)
                    {
                        dnsIp    = r.Value;
                        recordId = r.RecordId;
                    }
                }
            } catch (ServerException ex) {
                logger.Error("Server Error >> code : " + ex.ErrorCode + " | Error Message : " + ex.ErrorMessage);
            } catch (ClientException ex) {
                logger.Error("Client Error >> code : " + ex.ErrorCode + " | Error Message : " + ex.ErrorMessage);
            }
            if (dnsIp.Length == 0)
            {
                logger.Info("Can't Get Dns Record , Add New Record .");
                AddDomainRecordRequest reqAdd = new AddDomainRecordRequest();
                reqAdd.AcceptFormat = Aliyun.Acs.Core.Http.FormatType.JSON;
                reqAdd.DomainName   = domainName_;
                reqAdd.RR           = subDomainName_;
                reqAdd.Type         = "A";
                reqAdd.Value        = currentInternetIp;
                try {
                    //添加解析记录
                    AddDomainRecordResponse resAdd = client.GetAcsResponse(reqAdd);
                    logger.Info("\r\n Dns Record Add ...... 【OK】 \r\n New Dns Record Is : " + currentInternetIp);
                } catch (ServerException ex) {
                    logger.Error("Dns Record Add ...... 【Error】 \r\n Server Error >> code : " + ex.ErrorCode + " | Error Message : " + ex.ErrorMessage);
                } catch (ClientException ex) {
                    logger.Error("Dns Record Add ...... 【Error】 \r\n Client Error >> code : " + ex.ErrorCode + " | Error Message : " + ex.ErrorMessage);
                }
            }
            else
            {
                if (currentInternetIp == dnsIp)
                {
                    logger.Info("Current Internet Ip Is : " + currentInternetIp + " ,Same As Dns Record ...... 【Skip】");
                }
                else
                {
                    //更新记录
                    UpdateDomainRecordRequest reqUpdate = new UpdateDomainRecordRequest();
                    reqUpdate.AcceptFormat = Aliyun.Acs.Core.Http.FormatType.JSON;
                    reqUpdate.RecordId     = recordId;
                    reqUpdate.RR           = subDomainName_;
                    reqUpdate.Type         = "A";
                    reqUpdate.Value        = currentInternetIp;
                    try {
                        //更新解析记录
                        UpdateDomainRecordResponse resUpdate = client.GetAcsResponse(reqUpdate);
                        logger.Info("\r\n Update Dns  Record ...... 【OK】 \r\n New Dns Record Is : " + currentInternetIp);
                    } catch (ServerException ex) {
                        logger.Error("Dns Record Update ...... 【Error】 \r\n Server Error >> code : " + ex.ErrorCode + " | Error Message : " + ex.ErrorMessage);
                    } catch (ClientException ex) {
                        logger.Error("Dns Record Update ...... 【Error】 \r\n Client Error >> code : " + ex.ErrorCode + " | Error Message : " + ex.ErrorMessage);
                    }
                }
            }
        }
        public void UpdateDomainRecord(string currentIp)
        {
            //基础参数
            string regionId        = Options.Config.RegionId;
            string accessKeyId     = Options.Config.AccessKeyId;
            string accessKeySecret = Options.Config.AccessKeySecret;
            int    globalPageSize  = Options.Config.PageSize;

            //string domainName = "mydomain.com";
            //string rr = "www";
            //string currentIp = GetCurrentIp();

            Logger.LogDebug($"This computer's network IP address is \"{currentIp}\"");

            foreach (var domainRecord in Options.DomainRecords)
            {
                Logger.LogDebug($"Ready to update the domain name is \"{domainRecord.DomainName}\"");
                Logger.LogDebug($"The RR is \"{domainRecord.RR}\"");
                Logger.LogDebug($"Current DateTime is \"{DateTime.Now.ToLongDateTime()}\"");
                Logger.LogDebug(string.Empty);

                try
                {
                    int pageSize = domainRecord.PageSize > 0 ? domainRecord.PageSize : globalPageSize;
                    //初始化默认的ACS客户端
                    IClientProfile   clientProfile = DefaultProfile.GetProfile(regionId, accessKeyId, accessKeySecret);
                    DefaultAcsClient client        = new DefaultAcsClient(clientProfile);

                    //初始化指定域名的解析记录信息查询请求
                    DescribeDomainRecordsRequest describeDomainRecordsRequest = new DescribeDomainRecordsRequest
                    {
                        PageNumber  = 1,
                        PageSize    = pageSize,
                        RRKeyWord   = domainRecord.RR,
                        TypeKeyWord = Type,
                        DomainName  = domainRecord.DomainName
                                      //AcceptFormat = FormatType.JSON
                    };
                    //执行并且获取查询指定域名的解析记录信息的响应结果
                    DescribeDomainRecordsResponse describeDomainRecordsResponse = client.GetAcsResponse(describeDomainRecordsRequest);
                    Logger.LogDebug($"No.0 <<DescribeDomainRecordsResponse>> The request id is \"{describeDomainRecordsResponse.RequestId}\"");
                    Logger.LogDebug($"No.0 <<DescribeDomainRecordsResponse>> Total number of records matching your query is \"{describeDomainRecordsResponse.TotalCount}\"");
                    Logger.LogDebug($"No.0 <<DescribeDomainRecordsResponse>> The raw content is \"{Encoding.UTF8.GetString(describeDomainRecordsResponse.HttpResponse.Content)}\"");
                    Logger.LogDebug(string.Empty);

                    if (describeDomainRecordsResponse.TotalCount.HasValue && describeDomainRecordsResponse.TotalCount.Value > 0 && describeDomainRecordsResponse.DomainRecords.Any())
                    {
                        //待更新的解析记录总列表
                        var domainRecords = describeDomainRecordsResponse.DomainRecords;

                        //总页数
                        int totalPage = Convert.ToInt32(describeDomainRecordsResponse.TotalCount.Value / pageSize);
                        if ((describeDomainRecordsResponse.TotalCount.Value % pageSize) > 0)
                        {
                            totalPage++;
                        }

                        //当总页数大于1时,表示还有下一页
                        if (totalPage > 1)
                        {
                            //从第二页开始获取待更新的解析记录列表
                            for (int pageNumber = 2; pageNumber <= totalPage; pageNumber++)
                            {
                                describeDomainRecordsRequest.PageNumber = pageNumber;
                                describeDomainRecordsResponse           = client.GetAcsResponse(describeDomainRecordsRequest);
                                if (describeDomainRecordsResponse.DomainRecords.Any())
                                {
                                    //添加到待解析记录总列表
                                    domainRecords.AddRange(describeDomainRecordsResponse.DomainRecords);
                                }
                            }
                        }

                        //更新指定域名的解析记录值
                        int index = 0;
                        foreach (var item in domainRecords)
                        {
                            index++;
                            if (item.Value == currentIp)
                            {
                                Logger.LogDebug($"No.{index} <<DescribeDomainRecordsResponse>> The record id is \"{item.RecordId}\", Domain Name is \"{item.DomainName}\", RR is \"{item.RR}\", value is \"{item.Value}\", does not need to be updated");
                                Logger.LogDebug(string.Empty);
                                continue;
                            }

                            //初始化指定域名的解析记录更新请求
                            UpdateDomainRecordRequest updateDomainRecordRequest = new UpdateDomainRecordRequest
                            {
                                RecordId = item.RecordId,
                                RR       = item.RR,
                                Type     = item.Type,
                                Value    = currentIp
                            };
                            //执行并且获取更新指定域名的解析记录的响应结果
                            UpdateDomainRecordResponse updateDomainRecordResponse = client.GetAcsResponse(updateDomainRecordRequest);
                            Logger.LogDebug($"No.{index} <<UpdateDomainRecordRequest>> updating the domain name is \"{item.RR}.{item.DomainName}\"");
                            Logger.LogDebug($"No.{index} <<UpdateDomainRecordRequest>> Before updating the record value is \"{item.Value}\"");
                            Logger.LogDebug($"No.{index} <<UpdateDomainRecordRequest>> Updated the record value is \"{currentIp}\"");
                            Logger.LogDebug($"No.{index} <<UpdateDomainRecordRequest>> The request id is \"{updateDomainRecordResponse.RequestId}\"");
                            Logger.LogDebug($"No.{index} <<UpdateDomainRecordRequest>> The record id is \"{updateDomainRecordResponse.RecordId}\"");
                            Logger.LogDebug(string.Empty);
                        }
                    }

                    Logger.LogDebug($"Update \"{domainRecord.DomainName}\" completed!");
                    Logger.LogDebug(string.Empty);
                }
                catch (ServerException ex)
                {
                    Logger.LogDebug(0, ex, $"Throw {nameof(ServerException)}");
                }
                catch (ClientException ex)
                {
                    Logger.LogDebug(0, ex, $"Throw {nameof(ClientException)}");
                }
                catch (Exception ex)
                {
                    Logger.LogDebug(0, ex, $"Throw {nameof(Exception)}");
                }
            }

            Logger.LogDebug("Update all completed!");
        }
Exemplo n.º 18
0
        public void CheckOrChangeAnalysis(object sender, ElapsedEventArgs e)
        {
            if (!File.Exists(_logPath))
            {
                File.Create(_logPath);
            }

            var streamWriter = new StreamWriter(_logPath, true);

            // var configs = File.ReadAllLines("config.txt");
            try
            {
                // 默认修改在Service App.Config 修改 也可以手动指定
                var accessKeyId     = ConfigurationManager.AppSettings["AccessKeyId"]; //Access Key ID,如 DR2DPjKmg4ww0e79
                var accessKeySecret =
                    ConfigurationManager.AppSettings["AccessKeySecret"];
                ;                                                                //Access Key Secret,如 ysHnd1dhWvoOmbdWKx04evlVEdXEW7
                var domainName = ConfigurationManager.AppSettings["DomainName"]; //域名,如 google.com
                var rr         = ConfigurationManager.AppSettings["RR"];         //子域名,如 www
                var ttl        = ConfigurationManager.AppSettings["TTL"];        // TTL 时间 单位秒 免费最低120 2分钟 收费最低1秒

                var aliyunClient = new DefaultAliyunClient("http://dns.aliyuncs.com/", accessKeyId, accessKeySecret);
                var req          = new DescribeDomainRecordsRequest {
                    DomainName = domainName
                };
                var response = aliyunClient.Execute(req);

                // 筛选只有A类解析,且前缀为设置的前缀
                var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == rr && rec.Type == "A");
                if (updateRecord == null)
                {
                    return;
                }

                var httpClient = new HttpClient(new HttpClientHandler
                {
                    AutomaticDecompression =
                        DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None
                });
                httpClient.DefaultRequestHeaders.UserAgent.Add(
                    new ProductInfoHeaderValue(new ProductHeaderValue("aliyun-ddns-client-csharp")));
                // 默认修改在Service App.Config 修改 也可以手动指定 获取本地外网IP的地址
                var htmlSource = httpClient.GetStringAsync(ConfigurationManager.AppSettings["IpServer"]).Result;

                var ip = Regex.Match(htmlSource,
                                     @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))",
                                     RegexOptions.IgnoreCase).Value;

                if (updateRecord.Value == ip)
                {
                    return;
                }

                if (!int.TryParse(ttl, out var ttlInt))
                {
                    ttlInt = 120;
                }

                var changeValueRequest = new UpdateDomainRecordRequest
                {
                    RecordId = updateRecord.RecordId,
                    Value    = ip,
                    Type     = "A",
                    RR       = rr,
                    TTL      = ttlInt
                };
                aliyunClient.Execute(changeValueRequest);

                streamWriter.WriteLine(
                    $"Time:{DateTime.Now}\r\n   Before Ip:{updateRecord.Value}\r\n   Change Ip:{ip}");
            }
            catch (Exception ex)
            {
                streamWriter.WriteLine(ex.ToString());
            }
            finally
            {
                streamWriter.Close();

                streamWriter = null;
            }
        }
Exemplo n.º 19
0
        private static void Main(string[] args)
        {
            try
            {
                var configs         = File.ReadAllLines("config.txt");
                var accessKeyId     = configs[0].Trim();    //Access Key ID,如 DR2DPjKmg4ww0e79
                var accessKeySecret = configs[1].Trim();    //Access Key Secret,如 ysHnd1dhWvoOmbdWKx04evlVEdXEW7
                var domainName      = configs[2].Trim();    //域名,如 google.com
                var rr = configs[3].Trim();                 //子域名,如 www
                println("正在更新记录:" + rr + ",域名:" + domainName);

                var aliyunClient = new DefaultAliyunClient("http://dns.aliyuncs.com/", accessKeyId, accessKeySecret);
                var req          = new DescribeDomainRecordsRequest()
                {
                    DomainName = domainName
                };
                var response = aliyunClient.Execute(req);

                var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == rr && rec.Type == "A");
                if (updateRecord == null)
                {
                    return;
                }
                println("目前域名IP:" + updateRecord.Value);

                //获取IP
#if NET35
                var ipRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["IpServer"]);
                ipRequest.AutomaticDecompression = DecompressionMethods.None | DecompressionMethods.GZip |
                                                   DecompressionMethods.Deflate;
                ipRequest.UserAgent = "aliyun-ddns-client-csharp";
                string htmlSource;
                using (var ipResponse = ipRequest.GetResponse())
                {
                    using (var responseStream = ipResponse.GetResponseStream())
                    {
                        using (var streamReader = new StreamReader(responseStream))
                        {
                            htmlSource = streamReader.ReadToEnd();
                        }
                    }
                }
#else
                var httpClient = new HttpClient(new HttpClientHandler
                {
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None,
                });
                httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("aliyun-ddns-client-csharp")));
                var htmlSource = httpClient.GetStringAsync(ConfigurationManager.AppSettings["IpServer"]).Result;
#endif
                var ip = Regex.Match(htmlSource, @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))", RegexOptions.IgnoreCase).Value;
                println("本机IP地址:" + ip);

                if (updateRecord.Value != ip)
                {
                    var changeValueRequest = new UpdateDomainRecordRequest()
                    {
                        RecordId = updateRecord.RecordId,
                        Value    = ip,
                        Type     = "A",
                        RR       = rr
                    };
                    aliyunClient.Execute(changeValueRequest);
                    println("IP地址更新完成。");
                }
                else
                {
                    println("IP地址无变化,退出。");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            //Thread.Sleep(5000);
        }
Exemplo n.º 20
0
        private static void Main(string[] args)
        {
            try
            {
                var configs         = File.ReadAllLines("config.txt");
                var accessKeyId     = configs[0].Trim();    //Access Key ID,如 DR2DPjKmg4ww0e79
                var accessKeySecret = configs[1].Trim();    //Access Key Secret,如 ysHnd1dhWvoOmbdWKx04evlVEdXEW7
                var domainName      = configs[2].Trim();    //域名,如 google.com
                var rr = configs[3].Trim();                 //子域名,如 www
                Console.WriteLine("Updating {0} of domain {1}", rr, domainName);

                var aliyunClient = new DefaultAliyunClient("http://dns.aliyuncs.com/", accessKeyId, accessKeySecret);
                var req          = new DescribeDomainRecordsRequest()
                {
                    DomainName = domainName
                };
                var response = aliyunClient.Execute(req);

                var updateRecord = response.DomainRecords.FirstOrDefault(rec => rec.RR == rr && rec.Type == "A");
                if (updateRecord == null)
                {
                    return;
                }
                Console.WriteLine("Domain record IP is " + updateRecord.Value);

                //获取IP
#if NET35
                var ipRequest = (HttpWebRequest)WebRequest.Create("http://www.ip.cn/");
                ipRequest.AutomaticDecompression = DecompressionMethods.None | DecompressionMethods.GZip |
                                                   DecompressionMethods.Deflate;
                ipRequest.UserAgent = "aliyun-ddns-client-csharp";
                string htmlSource;
                using (var ipResponse = ipRequest.GetResponse())
                {
                    using (var responseStream = ipResponse.GetResponseStream())
                    {
                        using (var streamReader = new StreamReader(responseStream))
                        {
                            htmlSource = streamReader.ReadToEnd();
                        }
                    }
                }
#else
                var httpClient = new HttpClient(new HttpClientHandler
                {
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None,
                });
                httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("aliyun-ddns-client-csharp")));
                var htmlSource = httpClient.GetStringAsync("http://www.ip.cn/").Result;
#endif
                var ip = Regex.Match(htmlSource, @"(?<=<code>)[\d\.]+(?=</code>)", RegexOptions.IgnoreCase).Value;
                Console.WriteLine("Current IP is " + ip);

                if (updateRecord.Value != ip)
                {
                    var changeValueRequest = new UpdateDomainRecordRequest()
                    {
                        RecordId = updateRecord.RecordId,
                        Value    = ip,
                        Type     = "A",
                        RR       = rr
                    };
                    aliyunClient.Execute(changeValueRequest);
                    Console.WriteLine("Update finished.");
                }
                else
                {
                    Console.WriteLine("IPs are same now. Exiting");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Thread.Sleep(5000);
        }
Exemplo n.º 21
0
        public override void Sync(SyncContext context)
        {
            var config = DomainConfigHelper.GetProviderInfo <AliyunConfig>(context.DomainConfigItem);

            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", config.Id, config.Secret);

            var client = new DefaultAcsClient(profile);

            client.SetConnectTimeoutInMilliSeconds(60000);
            client.SetReadTimeoutInMilliSeconds(60000);

            var item = context.DomainConfigItem;

            // 更新解析记录使用的请求,为了便于 catch 时获取相关数据,所以定义在 try 块外面
            UpdateDomainRecordRequest updateRequest = null;

            try
            {
                string recordId;
                string rr;
                string originalIP;

                var domainName       = item.Domain;
                var domainTypeString = item.Type.ToString();

                // 先用获取子域名的 API DescribeSubDomainRecordsRequest 进行尝试,如果查询不到该子域名,再尝试使用 DescribeDomainRecordsRequest 进行根域名查询
                Console.WriteLine($"Try use sub domain api to search. SubDomain = {domainName}, Type = {domainTypeString}");

                var subQueryRequest = new DescribeSubDomainRecordsRequest
                {
                    SubDomain = domainName,
                    Type      = domainTypeString
                };

                var subQueryResponse = client.GetAcsResponse(subQueryRequest);
                if (subQueryResponse.TotalCount > 0)
                {
                    Console.WriteLine("Is sub domain");

                    // 虽然 DescribeSubDomainRecordsRequest 没有问题,安全起见还是过滤一下(具体问题参见后面 DescribeDomainRecordsRequest 的注释)
                    var result = subQueryResponse.DomainRecords.SingleOrDefault(d => d.Type == domainTypeString);
                    recordId   = result?.RecordId;
                    rr         = result?.RR;
                    originalIP = result?._Value;
                }
                else
                {
                    Console.WriteLine($"Not sub domain. Try use root domain api to search. SearchMode = EXACT, KeyWord = @, DomainName = {domainName}, TypeKeyWord = {domainTypeString}, Type = {domainTypeString}");

                    // 由于 Type 和 TypeKeyWord 属性实测没有作用,过滤不了域名类型
                    // 所以得到查询结果后还需要再手动过滤一次
                    var rootQueryRequest = new DescribeDomainRecordsRequest
                    {
                        SearchMode  = "EXACT",
                        DomainName  = domainName,
                        KeyWord     = "@",
                        TypeKeyWord = domainTypeString,
                        Type        = domainTypeString
                    };

                    var rootQueryResponse = client.GetAcsResponse(rootQueryRequest);
                    var result            = rootQueryResponse.DomainRecords.SingleOrDefault(d => d.Type == domainTypeString);
                    recordId   = result?.RecordId;
                    rr         = result?.RR;
                    originalIP = result?._Value;
                }

                Console.WriteLine($"Search succeed: id = {recordId}, RR = {rr}, Value = {originalIP}");

                if (recordId == null)
                {
                    throw new KeyNotFoundException($"Update failed: cannot find a record for the domain name {item.Domain}.");
                }

                var address = IPHelper.GetAddress(item.Interface, item.AddressFamily);
                Console.WriteLine($"Interface {item.Interface} {item.AddressFamily} address is {address}");

                updateRequest = new UpdateDomainRecordRequest
                {
                    RecordId = recordId,
                    RR       = rr,
                    Type     = domainTypeString,
                    _Value   = address
                };

                var updateResponse = client.GetAcsResponse(updateRequest);

                Console.WriteLine($"{item.Domain} updated successfully: {originalIP} -> {address}");

                item.LastSyncStatus            = SyncStatus.Success;
                item.LastSyncSuccessOriginalIP = originalIP;
                item.LastSyncSuccessCurrentIP  = address;
                item.LastSyncSuccessTime       = DateTime.Now;
            }
            catch (ClientException ex)
            {
                // 如果更新时返回了 DomainRecordDuplicate 错误
                // 有可能是本地记录的 LastSyncSuccessCurrentIP 和机器实际的 IP 以及域名解析提供商一侧的地址不匹配
                // 例如有段时间里程序没有执行,但 IP 发生了改变,就会造成 LastSyncSuccessCurrentIP 和提供商处的 IP 地址,以及实际地址不匹配)
                if (ex.ErrorCode == "DomainRecordDuplicate")
                {
                    item.LastSyncStatus = SyncStatus.Ignore;

                    if (updateRequest._Value != item.LastSyncSuccessCurrentIP)
                    {
                        item.LastSyncSuccessCurrentIP = updateRequest?._Value;

                        App.Out.WriteLine($"Update failed because the IP address recorded in the cache does not match the actual IP address and the IP address stored by the provider. The cache record has been updated, you can ignore this prompt.");

                        return;
                    }

                    App.Out.WriteLine($"{ex.ErrorMessage} You can ignore this prompt.");
                }
                else
                {
                    throw;
                }
            }
        }