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 foreach、while性能比较
Oct 15 PHP
php select,radio和checkbox默认选择的实现方法
May 15 PHP
php开发环境配置记录
Jan 14 PHP
mac下使用brew配置环境的步骤分享
May 23 PHP
php缓冲 output_buffering和ob_start使用介绍
Jan 30 PHP
PHP jQuery表单,带验证具体实现方法
Feb 15 PHP
PHP+MySQL修改记录的方法
Jan 21 PHP
CI框架整合smarty步骤详解
May 19 PHP
Laravel中使用FormRequest进行表单验证方法及问题汇总
Jun 19 PHP
为何说PHP引用是个坑,要慎用
Apr 02 PHP
PHP容器类的两种实现方式示例
Jul 24 PHP
Laravel框架实现的上传图片到七牛功能详解
Sep 06 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
用session做客户验证时的注意事项
2006/10/09 PHP
PHP学习资料汇总与网址
2007/03/16 PHP
PHPMYADMIN 简明安装教程 推荐
2010/03/07 PHP
解析crontab php自动运行的方法
2013/06/24 PHP
浅析Yii2中GridView常见操作
2016/04/22 PHP
jquery 学习笔记一
2010/04/07 Javascript
MooBox 基于Mootools的对话框插件
2012/01/20 Javascript
Js nodeType 属性全面解析
2013/11/14 Javascript
三种Node.js写文件的方式
2016/03/08 Javascript
提升页面加载速度的插件InstantClick
2017/09/12 Javascript
vue 将页面公用的头部组件化的方法
2017/12/18 Javascript
微信小程序实现animation动画
2018/01/26 Javascript
学习Vue组件实例
2018/04/28 Javascript
JavaScript引用类型Array实例分析
2018/07/24 Javascript
node.js使用redis储存session的方法
2018/09/26 Javascript
微信小程序网络请求实现过程解析
2019/11/06 Javascript
简单了解JS打开url的方法
2020/02/21 Javascript
如何利用nodejs实现命令行游戏
2020/11/24 NodeJs
以Python的Pyspider为例剖析搜索引擎的网络爬虫实现方法
2015/03/30 Python
Python基于回溯法子集树模板解决旅行商问题(TSP)实例
2017/09/05 Python
python正则实现计算器功能
2017/12/14 Python
python处理自动化任务之同时批量修改word里面的内容的方法
2019/08/23 Python
pandas实现将日期转换成timestamp
2019/12/07 Python
django数据模型(Model)的字段类型解析
2019/12/25 Python
Python TKinter如何自动关闭主窗口
2020/02/26 Python
Python常用断言函数实例汇总
2020/11/30 Python
纯CSS3实现圆角效果(含IE兼容解决方法)
2014/05/07 HTML / CSS
html5 分层屏幕适配的方法
2018/03/16 HTML / CSS
大学生村官任职感言
2014/01/09 职场文书
企业人事任命书
2014/06/05 职场文书
劳动竞赛口号
2014/06/16 职场文书
土地租赁意向书
2014/07/30 职场文书
干部职工纪律作风整改措施思想汇报
2014/10/11 职场文书
考试作弊检讨书范文
2015/01/27 职场文书
考勤制度通知
2015/04/25 职场文书
MySQL系列之一 MariaDB-server安装
2021/07/02 MySQL