使用阿里云Java SDK 实现 DDNS

本代码的实现前提:

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包, 通过命令行参数即可实现动态域名解析。再放入计划任务,自动更新……

猜你喜欢

转载自www.cnblogs.com/MonkChen/p/9213195.html