远程更新windows服务上hosts文件

简介: 远程更新windows服务上hosts文件

在liunx服务器上进行更新某windows服务器的hosts文件, 看起来有点难度。但经过我一番思考, 是这样的。

就是在要修改的远程windows客户端起个服务,  暴露自己接口, 更新对应的文件内容。


更新文件的代码如下, 大概的逻辑就是, 将要修改的文件读取出来,然后判断要写入的内容是否存在该文件中,若是存在该内容,则修改对应的内容,hosts文件内容都是ip对应着相应的域名,  只要获取到对应的ip和域名做对应的更新修改就好了。

/**
     * 获取host文件路径
     *
     * @return
     */
    public static String getHostFile() {
        String fileName = null;
        // 判断系统
        if ("linux".equalsIgnoreCase(System.getProperty("os.name"))) {
            fileName = "/etc/hosts";
        } else {
            fileName = System.getenv("windir") + "\\system32\\drivers\\etc\\hosts";
            // fileName = "C:\\selenium\\hosts";
            // fileName = "D:\\MacOs\\hosts";
        }
        return fileName;
    }

 

/**
     * 根据输入IP和Domain,更新host文件中的某个host配置
     *
     * @param ip
     * @param domain
     * @return
     */
    public synchronized static boolean updateHost(String ip, String domain) {
        if (ip == null || ip.trim().isEmpty() || domain == null || domain.trim().isEmpty()) {
            throw new IllegalArgumentException("ERROR:ip & domain must be specified");
        }
        String splitter = " ";
        /**
         * Step1: 获取host文件
         */
        String fileName = getHostFile();
        List<?> hostFileDataLines = null;
        try {
            hostFileDataLines = FileUtils.readLines(new File(fileName));
        } catch (IOException 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 (StringUtils.isEmpty(strLine) || strLine.trim().equals("#")) {
                continue;
            }
            if (!strLine.startsWith("#")) {
                int index = strLine.indexOf(domain);
                // 如果行字符可以匹配上指定域名,则针对该行做操作
                if (index != -1) {
                    // 如果之前已经找到过一条,则说明当前line的域名已重复,
                    // 故删除当前line, 不将该条数据放到newLinesList中去
                    if (findFlag) {
                        updateFlag = true;
                        continue;
                    }
                    // 不然,则继续寻找
                    String[] array = strLine.trim().split(splitter);
                    for (int i = 1; i < array.length; i++) {
                        if (!domain.equalsIgnoreCase(array[i])) {
                            continue;
                        } else {
                            // domain 相同, ip不同
                            findFlag = true;
                            if (!array[0].equals(ip)) {
                                // IP不同,将匹配上的domain的ip 更新成设定好的IP地址
                                StringBuilder sb = new StringBuilder();
                                sb.append(ip).append(splitter);
                                for (int j = 1; i < array.length; i++) {
                                    sb.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 {
                FileUtils.writeLines(new File(fileName), newLinesList);
            } catch (IOException e) {
                System.out.println("Updating host file occurs error: " + e.getMessage());
                return false;
            }
        }
        return true;
    }

修改文件的接口放在远程服务器, 进行启动,暴露对应的接口。在服务端进行调用执行,做对应的修改更新。

相关实践学习
基于函数计算快速搭建Hexo博客系统
本场景介绍如何使用阿里云函数计算服务命令行工具快速搭建一个Hexo博客。
目录
相关文章
|
20天前
|
C# Windows
.NET开源免费的Windows快速文件搜索和应用程序启动器
今天大姚给大家分享一款.NET开源(MIT License)、免费、功能强大的Windows快速文件搜索和应用程序启动器:Flow Launcher。
|
1月前
|
Linux Shell Windows
通过Linux挂载Windows端NFS服务实现板端Linux传输文件到PC
通过Linux挂载Windows端NFS服务实现板端Linux传输文件到PC
|
1月前
|
Shell Windows
Windows服务器 开机自启动服务
Windows服务器 开机自启动服务
14 0
|
1月前
|
开发框架 数据安全/隐私保护 开发者
HBuilder开发者必备!Windows上传IPA文件的软件分享
HBuilder开发者必备!Windows上传IPA文件的软件分享
21 1
|
9天前
|
网络协议 安全 测试技术
Windows安装禅道系统结合Cpolar实现公网访问内网BUG管理服务
Windows安装禅道系统结合Cpolar实现公网访问内网BUG管理服务
|
9天前
|
存储 安全 文件存储
Windows系统本地部署HFS并结合内网穿透实现公网访问本地存储文件
Windows系统本地部署HFS并结合内网穿透实现公网访问本地存储文件
Windows系统本地部署HFS并结合内网穿透实现公网访问本地存储文件
|
16天前
|
Windows
【Windows】 手写脚本更快编辑hosts文件
【Windows】 手写脚本更快编辑hosts文件
15 0
|
1月前
|
Windows
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
149 0
|
1月前
|
Windows
Windows 命令提示符(CMD)操作(一):文件和目录管理
Windows 命令提示符(CMD)操作(一):文件和目录管理
42 0
|
Windows
如何删除windows中的服务
办法一: 用sc.exe这个Windows命令      开始——运行——cmd.exe,然后输入sc就可以看到了。使用办法很简单:sc delete "服务名" 方法二:直接进行注册表编辑(不推荐)   打开注册表编辑器,找到下面的键值:HKEY_LOCAL_MACHINE\SYSTEM\Cur...
677 0