惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
SegmentFault 最新的问题
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Attack and Defense Labs
Attack and Defense Labs
F
Full Disclosure
Vercel News
Vercel News
N
News | PayPal Newsroom
The GitHub Blog
The GitHub Blog
H
Hacker News: Front Page
H
Heimdal Security Blog
P
Privacy International News Feed
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News
N
Netflix TechBlog - Medium
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cisco Blogs
L
Lohrmann on Cybersecurity
D
Docker
Recent Announcements
Recent Announcements
Security Archives - TechRepublic
Security Archives - TechRepublic
人人都是产品经理
人人都是产品经理
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Proofpoint News Feed
T
Tailwind CSS Blog
C
Check Point Blog
博客园 - 叶小钗
Google Online Security Blog
Google Online Security Blog
Martin Fowler
Martin Fowler
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
S
Secure Thoughts
博客园 - Franky
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
P
Palo Alto Networks Blog
Latest news
Latest news
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog
Last Week in AI
Last Week in AI
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Cyberwarzone
Cyberwarzone
小众软件
小众软件
Cisco Talos Blog
Cisco Talos Blog
Hacker News: Ask HN
Hacker News: Ask HN
T
Threatpost
T
Tenable Blog
P
Privacy & Cybersecurity Law Blog
WordPress大学
WordPress大学

博客园 - MonkChen

Ehcache3.4 XML配置硬盘存储 Tesseract训练 Postgresql Jsonb字段内含数组属性的删除元素操作 Activiti开启SQL Log Drools mvel方言drl断点调试方法 Openfire 编译插件 mysql数据备份 Silverlight 缓存控制策略 Silverlight ComboBox with TreeView silverlight5 net.tcpBinding 跨域策略的解决 WCF CustomBinding 身份验证 CMF Android !No Launcher activity found错误 Android SDK Manager 无法获取列表的解决 Silverlight跨域调用gSoap/Java web service 以及wsdl文件的修改 gSOAP契约函数返回结构体(返回多个值) java jax-ws发布含有DateTime字段的实体的webservice gSoap中文乱码解决 RTMP协议
使用阿里云Java SDK 实现 DDNS
MonkChen · 2018-06-22 · via 博客园 - MonkChen

本代码的实现前提:

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>

代码:

package com.phipsoft.aliyun.ddns;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse.Record;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;


public class DDNS {
    static final String CHARSET_ENCONDING = "utf-8";
    static final String KEY_IP_URL = "-url";
    static final String KEY_IP_REGEX_PATTERN = "-reg";
    static final String KEY_ACCESS_KEY = "-k";
    static final String KEY_ACCESS_SECRET = "-s"; 
    static final String KEY_DOMAIN = "-d";
    static final String KEY_RR = "-rr";
            
    
    
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + ((param == null || param.isEmpty())? "" : ("?" + param));
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("contentType", CHARSET_ENCONDING);
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
           
            // 建立实际的连接
            connection.connect();
           
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), CHARSET_ENCONDING));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }   
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    
    private static final String getInternetIP(String url, String regexPattern) {
        String ret = null;
        String html = sendGet(url, null);
        Pattern pattern =  Pattern.compile(regexPattern);
        Matcher matcher = pattern.matcher(html);
        if(matcher.find()) {
            ret = matcher.group(0);
        }
        return ret;
    }
    
    private static void updateIP(Map<String, String> config) throws Exception {
        String ip = null;
        if(config.containsKey(KEY_IP_URL) && config.containsKey(KEY_IP_REGEX_PATTERN)) {
            ip = getInternetIP(config.get(KEY_IP_URL), config.get(KEY_IP_REGEX_PATTERN));
        }else {
            throw new RuntimeException("获取外网ip的参数不足");
        }
        IClientProfile clientProfile = DefaultProfile.getProfile("cn-hangzhou", config.get(KEY_ACCESS_KEY),  config.get(KEY_ACCESS_SECRET));
        IAcsClient  client = new DefaultAcsClient(clientProfile);
        DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
        request.setDomainName(config.get(KEY_DOMAIN));
        DescribeDomainRecordsResponse response;
        boolean flag = false;
        response = client.getAcsResponse(request);
        for(Record record : response.getDomainRecords()) {
            if(record.getRR().equalsIgnoreCase(config.get(KEY_RR))&&record.getType().equalsIgnoreCase("A")) {
                String old_ip = record.getValue();
                String cur_ip = ip;
                flag = true;
               if(!old_ip.equals(cur_ip)){
                   UpdateDomainRecordRequest udr_req = new UpdateDomainRecordRequest();
                   udr_req.setValue(cur_ip);
                   udr_req.setType(record.getType());  
                   udr_req.setTTL(record.getTTL());  
                   udr_req.setPriority(record.getPriority());  
                   udr_req.setLine(record.getLine());  
                   udr_req.setRecordId(record.getRecordId());   
                   udr_req.setRR(record.getRR());  
                   UpdateDomainRecordResponse udr_resp =  client.getAcsResponse(udr_req);
                   System.out.println(udr_resp.toString());
               }else{
                     System.out.println("不需要修改");
               } 
            }
        }
        if(flag == false) {
            throw new RuntimeException("无法找到RR="+config.get(KEY_RR));
        }
          
    }
    
    private static Map<String,String> parseArgs(String[] args){
        Map<String,String> ret = new HashMap<String, String>();
        for(int i=0;i<args.length;) {
            if(args[i].startsWith("-")) {
                ret.put(args[i], args[i+1]);
                i+=2;
            }else {
                i++;
            }
        }
        return ret;
    }
    
    
    /**
     * -k xxx -s xxxx -d xxx.cn -rr www -url xxxx -reg (\d+\.){3}\d+
     * @param args
     */
    public static void main(String[] args) {         
        try{
            Map<String,String> config = parseArgs(args);
            updateIP(config);
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

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