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和AJAX创建RSS聚合器的代码
Mar 13 PHP
关于UEditor编辑器远程图片上传失败的解决办法
Aug 31 PHP
基于PHP的简单采集数据入库程序
Jul 30 PHP
ThinkPHP提交表单时默认自动转义的解决方法
Nov 25 PHP
大家在抢红包,程序员在研究红包算法
Aug 31 PHP
详解PHP+AJAX无刷新分页实现方法
Nov 03 PHP
Yii2框架使用计划任务的方法
May 25 PHP
php实现批量修改文件名称的方法
Jul 23 PHP
PHP目录操作实例总结
Sep 27 PHP
Zend Framework路由器用法实例详解
Dec 11 PHP
php实现获取农历(阴历)、节日、节气的类与用法示例
Nov 20 PHP
Laravel Validator 实现两个或多个字段联合索引唯一
May 08 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
php读取mysql乱码,用set names XXX解决的原理分享
2011/12/29 PHP
PHP5.4中json_encode中文转码的变化小结
2013/01/30 PHP
php实现的常见排序算法汇总
2014/09/08 PHP
php处理复杂xml数据示例
2016/07/11 PHP
PHP中字符串长度的截取用法示例
2017/01/12 PHP
在父页面得到zTree已选中的节点的方法
2015/02/12 Javascript
jQuery获取剪贴板内容的方法
2016/06/16 Javascript
JS实现控制文本框的内容
2016/07/10 Javascript
AngularJS中watch监听用法分析
2016/11/04 Javascript
Angular2库初探
2017/03/01 Javascript
Grunt针对静态文件的压缩,版本控制打包的实例讲解
2017/09/29 Javascript
Node.js的进程管理的深入理解
2019/01/09 Javascript
解决vue组件props传值对象获取不到的问题
2019/06/06 Javascript
ant design pro中可控的筛选和排序实例
2020/11/17 Javascript
python海龟绘图实例教程
2014/07/24 Python
web.py在模板中输出美元符号的方法
2014/08/26 Python
为Python的web框架编写MVC配置来使其运行的教程
2015/04/30 Python
django接入新浪微博OAuth的方法
2015/06/29 Python
12步入门Python中的decorator装饰器使用方法
2016/06/20 Python
python3.4用循环往mysql5.7中写数据并输出的实现方法
2017/06/20 Python
Django框架设置cookies与获取cookies操作详解
2019/05/27 Python
Python3 requests文件下载 期间显示文件信息和下载进度代码实例
2019/08/16 Python
python logging日志模块原理及操作解析
2019/10/12 Python
Python 实现 T00ls 自动签到脚本代码(邮件+钉钉通知)
2020/07/06 Python
python opencv肤色检测的实现示例
2020/12/21 Python
详解如何解决canvas图片getImageData,toDataURL跨域问题
2018/09/17 HTML / CSS
GUESS盖尔斯法国官网:美国时尚品牌
2016/09/23 全球购物
宝拉珍选官方旗舰店:2%水杨酸精华液,收缩毛孔粗大和祛痘
2018/07/01 全球购物
酒店应聘自荐信
2013/11/09 职场文书
单位领导证婚词
2014/01/14 职场文书
市场营销个人求职信范文
2014/02/02 职场文书
个人承诺书
2014/03/26 职场文书
初中学生期末评语
2014/04/24 职场文书
给校长的建议书400字
2014/05/15 职场文书
党的群众路线教育实践活动查摆问题自查报告
2014/10/10 职场文书
在Python 中将类对象序列化为JSON
2022/04/06 Python