本代码的实现前提:

1.拥有阿里云域名,且获取了Access Key 及 Access Secret

2.能获取外网IP的页面地址(注意:ip138.com的实际包含ip地址为http://2018.ip138.com/ic.asp)

Maven依赖项:

  1. <dependencies>
  2. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
  3. <dependency>
  4. <groupId>org.apache.httpcomponents</groupId>
  5. <artifactId>httpclient</artifactId>
  6. <version>4.5.5</version>
  7. </dependency>
  8.  
  9. <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
  10. <dependency>
  11. <groupId>com.google.code.gson</groupId>
  12. <artifactId>gson</artifactId>
  13. <version>2.8.5</version>
  14. </dependency>
  15.  
  16. <!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
  17. <dependency>
  18. <groupId>com.aliyun</groupId>
  19. <artifactId>aliyun-java-sdk-core</artifactId>
  20. <version>4.0.2</version>
  21. </dependency>
  22.  
  23. <dependency>
  24. <groupId>com.aliyun</groupId>
  25. <artifactId>aliyun-java-sdk-alidns</artifactId>
  26. <version>2.0.6</version>
  27. </dependency>
  28.  
  29. </dependencies>

代码:

  1. package com.phipsoft.aliyun.ddns;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStreamReader;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. import java.util.regex.Matcher;
  10. import java.util.regex.Pattern;
  11.  
  12. import com.aliyuncs.DefaultAcsClient;
  13. import com.aliyuncs.IAcsClient;
  14. import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsRequest;
  15. import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
  16. import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse.Record;
  17. import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
  18. import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordResponse;
  19. import com.aliyuncs.profile.DefaultProfile;
  20. import com.aliyuncs.profile.IClientProfile;
  21.  
  22. public class DDNS {
  23. static final String CHARSET_ENCONDING = "utf-8";
  24. static final String KEY_IP_URL = "-url";
  25. static final String KEY_IP_REGEX_PATTERN = "-reg";
  26. static final String KEY_ACCESS_KEY = "-k";
  27. static final String KEY_ACCESS_SECRET = "-s";
  28. static final String KEY_DOMAIN = "-d";
  29. static final String KEY_RR = "-rr";
  30.  
  31. public static String sendGet(String url, String param) {
  32. String result = "";
  33. BufferedReader in = null;
  34. try {
  35. String urlNameString = url + ((param == null || param.isEmpty())? "" : ("?" + param));
  36. URL realUrl = new URL(urlNameString);
  37. // 打开和URL之间的连接
  38. URLConnection connection = realUrl.openConnection();
  39. // 设置通用的请求属性
  40. connection.setRequestProperty("accept", "*/*");
  41. connection.setRequestProperty("connection", "Keep-Alive");
  42. connection.setRequestProperty("contentType", CHARSET_ENCONDING);
  43. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  44.  
  45. // 建立实际的连接
  46. connection.connect();
  47.  
  48. in = new BufferedReader(new InputStreamReader(connection.getInputStream(), CHARSET_ENCONDING));
  49. String line;
  50. while ((line = in.readLine()) != null) {
  51. result += line;
  52. }
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56. // 使用finally块来关闭输入流
  57. finally {
  58. try {
  59. if (in != null) {
  60. in.close();
  61. }
  62. } catch (Exception e2) {
  63. e2.printStackTrace();
  64. }
  65. }
  66. return result;
  67. }
  68.  
  69. private static final String getInternetIP(String url, String regexPattern) {
  70. String ret = null;
  71. String html = sendGet(url, null);
  72. Pattern pattern = Pattern.compile(regexPattern);
  73. Matcher matcher = pattern.matcher(html);
  74. if(matcher.find()) {
  75. ret = matcher.group(0);
  76. }
  77. return ret;
  78. }
  79.  
  80. private static void updateIP(Map<String, String> config) throws Exception {
  81. String ip = null;
  82. if(config.containsKey(KEY_IP_URL) && config.containsKey(KEY_IP_REGEX_PATTERN)) {
  83. ip = getInternetIP(config.get(KEY_IP_URL), config.get(KEY_IP_REGEX_PATTERN));
  84. }else {
  85. throw new RuntimeException("获取外网ip的参数不足");
  86. }
  87. IClientProfile clientProfile = DefaultProfile.getProfile("cn-hangzhou", config.get(KEY_ACCESS_KEY), config.get(KEY_ACCESS_SECRET));
  88. IAcsClient client = new DefaultAcsClient(clientProfile);
  89. DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
  90. request.setDomainName(config.get(KEY_DOMAIN));
  91. DescribeDomainRecordsResponse response;
  92. boolean flag = false;
  93. response = client.getAcsResponse(request);
  94. for(Record record : response.getDomainRecords()) {
  95. if(record.getRR().equalsIgnoreCase(config.get(KEY_RR))&&record.getType().equalsIgnoreCase("A")) {
  96. String old_ip = record.getValue();
  97. String cur_ip = ip;
  98. flag = true;
  99. if(!old_ip.equals(cur_ip)){
  100. UpdateDomainRecordRequest udr_req = new UpdateDomainRecordRequest();
  101. udr_req.setValue(cur_ip);
  102. udr_req.setType(record.getType());
  103. udr_req.setTTL(record.getTTL());
  104. udr_req.setPriority(record.getPriority());
  105. udr_req.setLine(record.getLine());
  106. udr_req.setRecordId(record.getRecordId());
  107. udr_req.setRR(record.getRR());
  108. UpdateDomainRecordResponse udr_resp = client.getAcsResponse(udr_req);
  109. System.out.println(udr_resp.toString());
  110. }else{
  111. System.out.println("不需要修改");
  112. }
  113. }
  114. }
  115. if(flag == false) {
  116. throw new RuntimeException("无法找到RR="+config.get(KEY_RR));
  117. }
  118.  
  119. }
  120.  
  121. private static Map<String,String> parseArgs(String[] args){
  122. Map<String,String> ret = new HashMap<String, String>();
  123. for(int i=0;i<args.length;) {
  124. if(args[i].startsWith("-")) {
  125. ret.put(args[i], args[i+1]);
  126. i+=2;
  127. }else {
  128. i++;
  129. }
  130. }
  131. return ret;
  132. }
  133.  
  134. /**
  135. * -k xxx -s xxxx -d xxx.cn -rr www -url xxxx -reg (\d+\.){3}\d+
  136. * @param args
  137. */
  138. public static void main(String[] args) {
  139. try{
  140. Map<String,String> config = parseArgs(args);
  141. updateIP(config);
  142. }catch(Exception e){
  143. System.out.println(e);
  144. }
  145. }
  146. }

以上代码为简化运行环境,参数没做更多正确性检验, 生成可执行jar包, 通过命令行参数即可实现动态域名解析。再放入计划任务,自动更新……

使用阿里云Java SDK 实现 DDNS的更多相关文章

  1. 通过python将阿里云DNS解析作为DDNS使用

    通过python将阿里云DNS解析作为DDNS使用 脚本需要Python2.x运行 安装alidns python sdk sudo pip install aliyun-python-sdk-ali ...

  2. 阿里云 OCS SDK for NodeJS介绍

    阿里云 OCS SDK for NodeJS介绍 阿里云技术团队:熊亮 阿里云 SDK for NodeJS 是为 NodeJS 开发者提供使用阿里云各项服务的统一入口,由阿里云UED团队负责开发维护 ...

  3. 使用阿里云Python SDK管理ECS安全组

    准备工作 本机操作系统:CentOS7 python版本:python2.7.5 还需要准备如下信息: 一个云账号.Access Key ID.Access Key Secret.安全组ID.Regi ...

  4. 阿里云 .NET SDK Roa 和 Rpc 风格签名

    阿里云 .NET SDK Roa 和 Rpc 风格的签名 Demo,适用于自己不想用其提供的SDK,想用自己组装 Roa 和 Rpc 的签名方式. Roa 和 Rpc 的签名方式主要有以下几个不同点: ...

  5. 快速上手阿里云oss SDK

    使用阿里云oss SDK 依赖安装: pip install oss2 pip install aliyun-python-sdk-sts 版本最好是 2.7.5 或以上 如果要开启 crc64 循环 ...

  6. 揭秘阿里云 RTS SDK 是如何实现直播降低延迟和卡顿

    作者:予涛 途坦 这个夏天,没什么能够比一场酣畅淋漓的奥运比赛来的过瘾.但是,在视频平台直播观看比赛也有痛点:"卡顿" 和 "延时".受限于不同地域.复杂的网络 ...

  7. 阿里云直播SDK - .NET

    阿里云sdk:https://develop.aliyun.com/sdk/csharp?spm=5176.doc27234.2.4.QiJb9l Github:https://github.com/ ...

  8. thinkPHP中怎么使用阿里云的sdk

    使用阿里云官方给的方法总会报错 Class 'Home\Controller\DefaultProfile' not found 这样是因为namespace的原因,将aliyun sdk 放在con ...

  9. 从0开始搭建一个阿里云java部署环境

    一.购买服务器 https://www.aliyun.com/daily-act/ecs/activity_selection?spm=5176.8112568.738194.8.674c9ed53Y ...

随机推荐

  1. Buy or Build(UVa1151)

    如果枚举每个套餐,并每次都求最小生成树,总时间复杂度会很高,因而需要先求一次原图的最小生成树,则枚举套餐之后需要考虑的边大大减少了. 具体见代码: #include<cstdio> #in ...

  2. oracle data type

    NUMBER ( precision, scale) precision表示数字中的有效位.如果没有指定precision的话,Oracle将使用38作为精度. scale表示数字小数点右边的位数,s ...

  3. 16.python-I/O模型

    一.事件驱动模型1.什么是事件驱动模型:本身是一种编程范式,这里程序的执行是由外部事件来决定的.它的特点是包含一个事件循环,当外部事件发生时使用回调机制来触发相应的处理.常见的编程范式(单线程)同步以 ...

  4. python批量下载微信好友头像,微信头像批量下载

    #!/usr/bin/python #coding=utf8 # 自行下载微信模块 itchat 小和QQ496631085 import itchat,os itchat.auto_login() ...

  5. java中二维数组内存分配

    区分三种初始化方式: 格式一: 数据类型[][] 数组名 = new 数据类型[m][n]; m:表示这个二维数组有多少个一维数组. n:表示每一个一维数组的元素有多少个. //例:int arr[] ...

  6. 将连接数据库的JDBC提成BaseDao

    package com.shangke; import java.io.FileReader;import java.io.IOException;import java.io.InputStream ...

  7. Javascript 3.2

    对象的三种类型:1.用户定义对象:程序员自己创建的对象 2.内建对象:Javascript语言中的固定对象,如Array/Math/Data等 3.宿主对象:由浏览器提供的对象 BOM:浏览器对象模型 ...

  8. 1. Packet sniffers (包嗅探器 14个)

    十多年来,Nmap项目一直在编目网络安全社区最喜爱的工具. 2011年,该网站变得更加动态,提供打分,评论,搜索,排序和新工具建议表单. 本网站除了我们维护的那些工具(如Nmap安全扫描器,Ncat网 ...

  9. [工作积累] UE4 并行渲染的同步 - Sync between FParallelCommandListSet & FRHICommandListImmediate calls

    UE4 的渲染分为两个模式1.编辑器是同步绘制的 2.游戏里是FParallelCommandListSet并行派发的. mesh渲染也分两类,static mesh 使用TStaticMeshDra ...

  10. Actifio如何保护和管理Oracle-带外篇

    引言 本文提供CDS带外环境下相关配置,保护和恢复Oracle的所需步骤. 目的是提供Oracle数据库配置前的详细说明,Actifio环境下发现和配置Oracle数据库,执行还原和恢复,以及配置Or ...