java 动态修改阿里云域名解析,用于解决家用宽带公网ip经常变动问题

2021-01-05 01:29

阅读:530

标签:mave   except   records   aging   扫描   frame   ini   获取   date   

需要有java、maven、springboot、阿里云域名使用经验、以及拥有一个域名

pom文件

xml version="1.0" encoding="UTF-8"?>
project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    modelVersion>4.0.0modelVersion>

    groupId>com.binzgroupId>
    artifactId>update-domain-ipartifactId>
    version>0.0.1-SNAPSHOTversion>
    packaging>jarpackaging>

    name>update-domain-ipname>
    description>动态绑定ip到域名description>

    parent>
        groupId>org.springframework.bootgroupId>
        artifactId>spring-boot-starter-parentartifactId>
        version>2.3.0.RELEASEversion>
    parent>

    properties>
        project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        java.version>1.8java.version>
    properties>

    dependencies>
        dependency>
            groupId>org.springframework.bootgroupId>
            artifactId>spring-boot-starterartifactId>
        dependency>
        dependency>
            groupId>com.aliyungroupId>
            artifactId>aliyun-java-sdk-alidnsartifactId>
            version>2.0.7version>
        dependency>
        dependency>
            groupId>com.aliyungroupId>
            artifactId>aliyun-java-sdk-coreartifactId>
            version>4.1.1version>
        dependency>
        
        dependency>
            groupId>cn.hutoolgroupId>
            artifactId>hutool-httpartifactId>
            version>5.3.5version>
        dependency>

    dependencies>

    build>
        finalName>update-domain-ipfinalName>
        plugins>
            plugin>
                groupId>org.springframework.bootgroupId>
                artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>


project>

java代码:UpdateDoaminIpStarted

package com.binz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alidns.model.v20150109.DescribeSubDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeSubDomainRecordsResponse;
import com.aliyuncs.alidns.model.v20150109.DescribeSubDomainRecordsResponse.Record;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordRequest;
import com.aliyuncs.alidns.model.v20150109.UpdateDomainRecordResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import cn.hutool.http.HttpUtil;

@EnableScheduling
@SpringBootApplication
public class UpdateDoaminIpStarted {
    public static final String ACCESS_KEY_ID = "";//需要去阿里控制台 》 AccessKey管理 获取  
    public static final String ACCESS_KEY_SECRET = "";//需要去阿里控制台 》 AccessKey管理 获取 
    public static final String REGION_ID = "cn-hanghou";
    public static final String DOMIAN = "baidu.com";//域名  xxxx.com
    public static final Map UPDATE_DOMIANS;//需要修改的域名
    private static String CURRENT_IP = null;

    private static IAcsClient client = null;
    
    static {
        UPDATE_DOMIANS = new HashMap();
        UPDATE_DOMIANS.put("baidu.com", null);//根路径
        UPDATE_DOMIANS.put("mobile.baidu.com", null);
        UPDATE_DOMIANS.put("www.baidu.com", null);
        try {
            DefaultProfile.addEndpoint(REGION_ID,REGION_ID, "Alidns","alidns.aliyuncs.com");
        } catch (ClientException e) {
            e.printStackTrace();
        }
        IClientProfile profile = DefaultProfile.getProfile(REGION_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        client = new DefaultAcsClient(profile);
    }
    
    public static Record getSubDomainRecord(String subDomain) {
        DescribeSubDomainRecordsRequest request = new DescribeSubDomainRecordsRequest();
        DescribeSubDomainRecordsResponse response;
        request.setSubDomain(subDomain);
        try {
            response = client.getAcsResponse(request);
            List domainRecords = response.getDomainRecords();
            // {RR=mobile, recordId=4031722341639808, line=default, domainName=baidu.com,
            return domainRecords.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    private static String pingAndGetIp() {
        try {
            Set keySet = UPDATE_DOMIANS.keySet();
            Process process = Runtime.getRuntime().exec("ping "+ keySet.toArray()[0]);
            InputStream inputStream = process.getInputStream();
            InputStreamReader reader=new InputStreamReader(inputStream,"gbk");
            BufferedReader reader2=new BufferedReader(reader);
            String readLine =null;
            int i=0;
            while((readLine= reader2.readLine())!=null && i== 0) {
                if(readLine.indexOf("(") != -1){
                    readLine =readLine.substring(readLine.indexOf("(")+1, readLine.indexOf(")"));
                    break;
                }
            }
            process.destroyForcibly();
            return readLine;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
    public static void updateDomainIp() {
        String ip = getIp();
        if(CURRENT_IP == null) {
            CURRENT_IP = pingAndGetIp();
        }
        System.out.println("oldIp:"+CURRENT_IP+",newIp:"+ip);
        if(!ip.equals(CURRENT_IP)) {
            UpdateDomainRecordRequest request;
            UpdateDomainRecordResponse response;
            String aa = "";
            for (String updateDomian : UPDATE_DOMIANS.keySet()) {
                if(UPDATE_DOMIANS.get(updateDomian) == null) {
                    UPDATE_DOMIANS.put(updateDomian, getSubDomainRecord(updateDomian).getRecordId());
                }
                aa = updateDomian.replaceAll(DOMIAN, "").equals("") ? "@" : updateDomian.replaceAll("."+DOMIAN, "");
                request = new UpdateDomainRecordRequest();
                request.setRecordId(UPDATE_DOMIANS.get(updateDomian));
                request.setRR(aa);
                request.setType("A");
                request.setValue(ip);
                try {
                    response = client.getAcsResponse(request);
                    System.out.println("成功把"+updateDomian+"的域名的ip解析成"+ip+",历史ip为:"+CURRENT_IP);
                    System.out.println(response.getRequestId());
                } catch (ServerException e) {
                    e.printStackTrace();
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
            
        }
    }

    public static String getIp() {
        String ip =  HttpUtil.get("http://ip.3322.net");
        return ip;
    }
    
    /**
     * 3分钟一次
     */
    @Scheduled(cron = "0 */3 * * * *")
    public void scheduled() {
        UpdateDoaminIpStarted.updateDomainIp();
    }


    public static void main(String[] args) {
//        updateDomainIp();//直接执行
        SpringApplication.run(UpdateDoaminIpStarted.class, args); //boot运行方式
    }
}

 

 

maven 打成包过后,直接在内网  java -jar update-domain-ip.jar 即可,只要外网ip变动了就会改变,这个3分钟就扫描一次,对于及时性要高一些的,可以提高扫描的频率
外网都需要通过域名访问,ip变了也无所谓,反正你只关心域名就行了

java 动态修改阿里云域名解析,用于解决家用宽带公网ip经常变动问题

标签:mave   except   records   aging   扫描   frame   ini   获取   date   

原文地址:https://www.cnblogs.com/binz/p/12982711.html


评论


亲,登录后才可以留言!