PHP实现更改hosts文件的方法示例


Posted in PHP onAugust 08, 2017

本文实例讲述了PHP实现更改hosts文件的方法。分享给大家供大家参考,具体如下:

有这样一个需求,我有多个网址希望在不同的时候对应不同的 ip,如果一个个配 hosts,这工作显得有些繁琐。写了如下脚本来批量更改。

<?php
define('HOST_FILE', 'C:\Windows\System32\drivers\etc\hosts');
$hm = new HostManage(HOST_FILE);
$env = $argv[1];
if (empty($env)) {
    $hm->delAllGroup();
} else {
    $hm->addGroup($env);
}
class HostManage {
    // hosts 文件路径
    protected $file;
    // hosts 记录数组
    protected $hosts = array();
    // 配置文件路径,默认为 __FILE__ . '.ini';
    protected $configFile;
    // 从 ini 配置文件读取出来的配置数组
    protected $config = array();
    // 配置文件里面需要配置的域名
    protected $domain = array();
    // 配置文件获取的 ip 数据
    protected $ip = array();
    public function __construct($file, $config_file = null) {
        $this->file = $file;
        if ($config_file) {
          $this->configFile = $config_file;
        } else {
          $this->configFile = __FILE__ . '.ini';
        }
        $this->initHosts()
            ->initCfg();
    }
    public function __destruct() {
        $this->write();
    }
    public function initHosts() {
        $lines = file($this->file);
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line) || $line[0] == '#') {
                continue;
            }
            $item = preg_split('/\s+/', $line);
            $this->hosts[$item[1]] = $item[0];
        }
        return $this;
    }
    public function initCfg() {
        if (! file_exists($this->configFile)) {
            $this->config = array();
        } else {
            $this->config = (parse_ini_file($this->configFile, true));
        }
        $this->domain = array_keys($this->config['domain']);
        $this->ip = $this->config['ip'];
        return $this;
    }
    /**
     * 删除配置文件里域的 hosts
     */
    public function delAllGroup() {
        foreach ($this->domain as $domain) {
            $this->delRecord($domain);
        }
    }
    /**
     * 将域配置为指定 ip
     * @param type $env
     * @return \HostManage
     */
    public function addGroup($env) {
        if (! isset($this->ip[$env])) {
            return $this;
        }
        foreach ($this->domain as $domain) {
            $this->addRecord($domain, $this->ip[$env]);
        }
        return $this;
    }
    /**
     * 添加一条 host 记录
     * @param type $ip
     * @param type $domain
     */
    function addRecord($domain, $ip) {
        $this->hosts[$domain] = $ip;
        return $this;
    }
    /**
     * 删除一条 host 记录
     * @param type $domain
     */
    function delRecord($domain) {
        unset($this->hosts[$domain]);
        return $this;
    }
    /**
     * 写入 host 文件
     */
    public function write() {
        $str = '';
        foreach ($this->hosts as $domain => $ip) {
            $str .= $ip . "\t" . $domain . PHP_EOL;
        }
        file_put_contents($this->file, $str);
        return $this;
    }
}

示例配置文件如下:

# 域名
[domain]
a.example.com=1 # 请无视这个 =1,因为使用了 parse_ini_file 这个函数来解析,如果后面不带值,就获取不到这条记录了
b.example.com=1
c.example.com=1
# ip 记录
[ip]
local=127.0.0.1
dev=192.168.1.100

使用方法:

php hosts.php local # 域名将指向本机 127.0.0.1
php hosts.php dev # 域名将指向开发机 192.168.1.100
php hosts.php # 删除域名的 hosts 配置

写完后,发现,这明明就是只需要一次查找替换就能完成的工作嘛

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
php中文本数据翻页(留言本翻页)
Oct 09 PHP
10条PHP编程习惯助你找工作
Sep 29 PHP
Ha0k 0.3 PHP 网页木马修改版
Oct 11 PHP
PHP中10个不常见却非常有用的函数
Mar 21 PHP
php 5.3.5安装memcache注意事项小结
Apr 12 PHP
关于php循环跳出的问题
Jul 01 PHP
PHP中遇到BOM、编码导致json_decode函数无法解析问题
Jul 02 PHP
PHP使用pear自带的mail类库发邮件的方法
Jul 08 PHP
详解php魔术方法(Magic methods)的使用方法
Feb 14 PHP
分析PHP中单双引号的误区和双引号小隐患
Jul 19 PHP
关于PHP通用返回值设置方法
Mar 31 PHP
PHP之多条件混合筛选功能的实现方法
Oct 09 PHP
PHP编程实现阳历转换为阴历的方法实例
Aug 08 #PHP
PHP数据分析引擎计算余弦相似度算法示例
Aug 08 #PHP
Eclipse PHPEclipse 配置的具体步骤
Aug 08 #PHP
PHP 文件锁与进程锁的使用示例
Aug 07 #PHP
PHP实现找出有序数组中绝对值最小的数算法分析
Aug 07 #PHP
php基于session锁防止阻塞请求的方法分析
Aug 07 #PHP
在Yii2特定页面如何禁用调试工具栏Debug Toolbar详解
Aug 07 #PHP
You might like
千呼万唤始出来,DOTA2勇士令状不朽宝藏Ⅱ现已推出
2020/08/25 DOTA
PHP文件读写操作之文件读取方法详解
2011/01/13 PHP
php 缩略图实现函数代码
2011/06/23 PHP
preg_match_all使用心得分享
2014/01/31 PHP
php中simplexml_load_string使用实例分享
2014/02/13 PHP
php中base64_decode与base64_encode加密解密函数实例
2014/11/24 PHP
关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题
2015/12/21 PHP
PHP怎样用正则抓取页面中的网址
2016/08/09 PHP
PHP面向对象五大原则之开放-封闭原则(OCP)详解
2018/04/04 PHP
PHP 计算两个时间段之间交集的天数示例
2019/10/24 PHP
jQuery 行级解析读取XML文件(附源码)
2009/10/12 Javascript
jquery showModelDialog的使用方法示例详解
2013/11/19 Javascript
js判断手机端(Android手机还是iPhone手机)
2015/07/22 Javascript
JavaScript时间操作之年月日星期级联操作
2016/01/15 Javascript
AngularJS 模块详解及简单实例
2016/07/28 Javascript
JavaScript原生数组Array常用方法
2017/04/06 Javascript
node通过npm写一个cli命令行工具
2017/10/12 Javascript
微信小程序之圆形进度条实现思路
2018/02/22 Javascript
Vue强制组件重新渲染的方法讨论
2020/02/03 Javascript
使用JavaScript实现贪吃蛇游戏
2020/09/29 Javascript
详解Vue2的diff算法
2021/01/06 Vue.js
[01:21]DOTA2 新英雄 森海飞霞
2020/12/18 DOTA
python模块简介之有序字典(OrderedDict)
2016/12/01 Python
Python使用sklearn库实现的各种分类算法简单应用小结
2019/07/04 Python
Python3简单爬虫抓取网页图片代码实例
2019/08/26 Python
linux下python中文乱码解决方案详解
2019/08/28 Python
详细整理python 字符串(str)与列表(list)以及数组(array)之间的转换方法
2019/08/30 Python
python3.7环境下安装Anaconda的教程图解
2019/09/10 Python
Windows平台Python编程必会模块之pywin32介绍
2019/10/01 Python
马来西亚网上购物:Youbeli
2018/03/30 全球购物
UNDONE手表官网:世界领先的定制手表品牌
2018/11/13 全球购物
大学生专科毕业生自我评价
2013/11/17 职场文书
应届行政管理专业个人自我评价
2013/12/28 职场文书
产品包装策划方案
2014/05/18 职场文书
Django 实现jwt认证的示例
2021/04/30 Python
Element-ui Layout布局(Row和Col组件)的实现
2021/12/06 Vue.js