12月9

java修改和添加hosts文件记录

| |
18:01编程杂谈  From: 本站原创
公司有个项目不能解析内网所以需要对本地hosts文件进行修改,添加一条本地域名解析记录,如果让客户去操作,很容易破坏掉原先的hosts文件,用户只需要以管理员权限运行即可,如果记录存在则替换掉。
由于办公电脑都使用信创麒麟的系统,所以最好做一个deb的安装包,通过程序写修改的,在信创麒麟的系统电脑下载安装即可执行。
下面是实现逻辑,要将java打包成deb安装包就需要使用jdeb的maven插件来打包。
我使用的是1.8的版本,具体配置就不贴上来了,需要的联系我。
               <artifactId>jdeb</artifactId>
                <groupId>org.vafer</groupId>
                <version>1.8</version>


package com.nine.rivers.jdeb;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
* @Description 不破坏原有hosts文件,支持新host绑定或修改支持host解绑
* @Date 2022/12/9 16:42
* @Author heck
**/
public class HostUtil {

    public static final String LINUX = "linux";
    public static final String LINUX_HOSTS_PATH = "/etc/hosts";
    public static final String WINDIR = "windir";
    public static final String WIN_HOSTS_PATH = "\\system32\\drivers\\etc\\hosts";
    public static final String OS_NAME = "os.name";

    /**
     * 获取host文件路径
     *
     * @return
     */
    public static String getHostFile() {
        String fileName = null;
        // 判断系统
        if (LINUX.equalsIgnoreCase(System.getProperty(OS_NAME))) {
            fileName = LINUX_HOSTS_PATH;
        } else {
            fileName = System.getenv(WINDIR) + WIN_HOSTS_PATH;
        }
        return fileName;
    }

    /**
     * 根据输入IP和Domain,删除host文件中的某个host配置
     *
     * @param ip
     * @param domain
     * @return
     */
    public synchronized static boolean deleteHost(String ip, String domain) {
        if (StrUtil.isBlank(ip) || StrUtil.isEmpty(ip.trim())
                || StrUtil.isBlank(domain) || StrUtil.isEmpty(domain.trim())) {
            throw new IllegalArgumentException("ERROR: ip & domain must be specified");
        }

        String splitTer = " ";

        /**
         * Step1: 获取host文件
         */
        String fileName = getHostFile();
        List<?> hostFileDataLines = null;
        try {
            hostFileDataLines = FileUtil.readUtf8Lines(new File(fileName));
        } catch (IORuntimeException e) {
            System.out.println("Reading host file occurs error: " + e.getMessage());
            return false;
        }

        /**
         * Step2: 解析host文件,如果指定域名不存在,则Ignore,如果已经存在,则直接删除该行配置
         */
        List<String> newLinesList = new ArrayList<String>();
        // 标识本次文件是否有更新,比如如果指定的IP和域名已经在host文件中存在,则不用再写文件
        boolean updateFlag = false;
        for (Object line : hostFileDataLines) {
            String strLine = line.toString();
            // 将host文件中的空行或无效行,直接去掉
            if (StrUtil.isEmpty(strLine) || strLine.trim().equals("#")) {
                continue;
            }
            // 如果没有被注释掉,则
            if (!strLine.trim().startsWith("#")) {
                strLine = strLine.replaceAll("", splitTer);
                int index = strLine.toLowerCase().indexOf(domain.toLowerCase());
                // 如果行字符可以匹配上指定域名,则针对该行做操作
                if (index != -1) {
                    // 匹配到相同的域名,直接将整行数据干掉
                    updateFlag = true;
                    continue;
                }
            }
            // 如果没有匹配到,直接将当前行加入代码中
            newLinesList.add(strLine);
        }

        /**
         * Step3: 将更新写入host文件中去
         */
        if (updateFlag) {
            try {
                FileUtil.writeUtf8Lines(newLinesList, new File(fileName));
            } catch (IORuntimeException e) {
                System.out.println("Updating host file occurs error: " + e.getMessage());
                return false;
            }
        }
        return true;
    }


    /**
     * 根据输入IP和Domain,更新host文件中的某个host配置
     *
     * @param ip
     * @param domain
     * @return
     */
    public synchronized static boolean updateHost(String ip, String domain) {
        // Security.setProperty("networkaddress.cache.ttl", "0");
        // Security.setProperty("networkaddress.cache.negative.ttl", "0");

        if (StrUtil.isBlank(ip) || StrUtil.isEmpty(ip.trim())
                || StrUtil.isBlank(domain) || StrUtil.isEmpty(domain.trim())) {
            throw new IllegalArgumentException("ERROR: ip & domain must be specified");
        }

        String splitTer = " ";

        /**
         * Step1: 获取host文件
         */
        String fileName = getHostFile();
        List<?> hostFileDataLines = null;
        try {
            hostFileDataLines = FileUtil.readUtf8Lines(new File(fileName));
        } catch (IORuntimeException e) {
            System.out.println("Reading host file occurs error: " + e.getMessage());
            return false;
        }

        /**
         * Step2: 解析host文件,如果指定域名不存在,则追加,如果已经存在,则修改IP进行保存
         */
        List<String> newLinesList = new ArrayList<String>();
        // 指定domain是否存在,如果存在,则不追加
        boolean findFlag = false;
        // 标识本次文件是否有更新,比如如果指定的IP和域名已经在host文件中存在,则不用再写文件
        boolean updateFlag = false;
        for (Object line : hostFileDataLines) {
            String strLine = line.toString();
            // 将host文件中的空行或无效行,直接去掉
           /* if (StrUtil.isEmpty(strLine) || strLine.trim().equals("#")) {
                continue;
            }*/
            if (!strLine.startsWith("#")) {
                //strLine = strLine.replaceAll("", splitTer);
                int index = strLine.toLowerCase().indexOf(domain.toLowerCase());
                // 如果行字符可以匹配上指定域名,则针对该行做操作
                if (index != -1) {
                    // 如果之前已经找到过一条,则说明当前line的域名已重复,
                    // 故删除当前line, 不将该条数据放到newLinesList中去
                    if (findFlag) {
                        updateFlag = true;
                        continue;
                    }
                    // 不然,则继续寻找
                    String[] array = strLine.trim().split(splitTer);
                    Boolean isMatch = false;
                    for (int i = 1; i < array.length; i++) {
                        if (domain.equalsIgnoreCase(array[i]) == false) {
                            continue;
                        } else {
                            findFlag = true;
                            isMatch = true;
                            // IP相同,则不更新该条数据,直接将数据放到newLinesList中去
                            if (array[0].equals(ip) == false) {
                                // IP不同,将匹配上的domain的ip 更新成设定好的IP地址
                                StringBuilder sb = new StringBuilder();
                                sb.append(ip);
                                for (int j = 1; i < array.length; i++) {
                                    sb.append(splitTer).append(array[j]);
                                }
                                strLine = sb.toString();
                                updateFlag = true;
                            }
                        }
                    }
                }
            }
            // 如果有更新,则会直接更新到strLine中去
            // 故这里直接将strLine赋值给newLinesList
            newLinesList.add(strLine);
        }

        /**
         * Step3: 如果没有任何Host域名匹配上,则追加
         */
        if (!findFlag) {
            newLinesList.add(new StringBuilder(ip).append(splitTer).append(domain).toString());
        }

        /**
         * Step4: 不管三七二十一,写设定文件
         */
        if (updateFlag || !findFlag) {
            try {
                FileUtil.writeUtf8Lines(newLinesList, new File(fileName));
            } catch (IORuntimeException e) {
                System.out.println("Updating host file occurs error: " + e.getMessage());
                return false;
            }
        }
        return true;
    }

}


来源:Heck's Blog
地址:https://www.heckjj.com/post/636/
转载时须以链接形式注明作者和原始出处及本声明,否则将追究法律责任,谢谢配合!
阅读(44) | 评论(0) | 引用(0)