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中通过smtp发邮件的类,测试通过
Jan 22 PHP
dedecms模板标签代码官方参考
Mar 17 PHP
php 特殊字符处理函数
Sep 05 PHP
PHP is_dir() 判断给定文件名是否是一个目录
May 10 PHP
php+xml编程之xpath的应用实例
Jan 24 PHP
PHP预定义变量9大超全局数组用法详解
Apr 23 PHP
php版银联支付接口开发简明教程
Oct 14 PHP
thinkphp中AJAX返回ajaxReturn()方法分析
Dec 06 PHP
PHP实现二维数组去重功能示例
Jan 12 PHP
django中的ajax组件教程详解
Oct 18 PHP
PHP实现倒计时功能
Nov 16 PHP
PHP面试题 wakeup魔法 Ezpop pop序列化与反序列化
Apr 11 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做的端口嗅探器--可以指定网站和端口
2006/10/09 PHP
php学习之简单计算器实现代码
2011/06/09 PHP
将时间以距今多久的形式表示,PHP,js双版本
2012/09/25 PHP
非常精妙的PHP递归调用与静态变量使用
2012/12/16 PHP
ueditor 1.2.6 使用方法说明
2013/07/24 PHP
php备份数据库类分享
2015/04/14 PHP
ThinkPHP的SAE开发相关注意事项详解
2016/10/09 PHP
php写app接口并返回json数据的实例(分享)
2017/05/20 PHP
JS 操作符整理[推荐收藏]
2011/11/15 Javascript
js异常捕获方法介绍
2013/04/10 Javascript
js形成页面的一种遮罩效果实例代码
2014/01/04 Javascript
JavaScript学习笔记之JS对象
2015/01/22 Javascript
jQuery实现iframe父窗体和子窗体的相互调用
2016/06/17 Javascript
AngularJS教程之环境设置
2016/08/16 Javascript
微信小程序图表插件(wx-charts)实例代码
2017/01/17 Javascript
Vue开发中整合axios的文件整理
2017/04/29 Javascript
使用vue-router为每个路由配置各自的title
2018/07/30 Javascript
Vue 解决路由过渡动画抖动问题(实例详解)
2020/01/05 Javascript
jQuery实现简单飞机大战
2020/07/05 jQuery
[00:31]DOTA2荣耀之路7:Miracle-空血无敌斩
2018/05/31 DOTA
Python的Socket编程过程中实现UDP端口复用的实例分享
2016/03/19 Python
Python中的左斜杠、右斜杠(正斜杠和反斜杠)
2016/08/30 Python
详解flask入门模板引擎
2018/07/18 Python
python 高效去重复 支持GB级别大文件的示例代码
2018/11/08 Python
详解爬虫被封的问题
2019/04/23 Python
python批量读取文件名并写入txt文件中
2020/09/05 Python
Python 音频生成器的实现示例
2019/12/24 Python
tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this T
2020/06/22 Python
意大利网上购书网站:Libraccio.it
2021/02/03 全球购物
美国最大最全的亚洲购物网站:美国亚米网(Yamibuy)
2020/05/05 全球购物
2014年最新学校运动会广播稿
2014/09/17 职场文书
祖国在我心中演讲稿600字
2014/09/23 职场文书
医院见习总结
2015/06/24 职场文书
创业计划书之个人工作室
2019/08/22 职场文书
Python的flask接收前台的ajax的post数据和get数据的方法
2021/04/12 Python
vue使用refs获取嵌套组件中的值过程
2022/03/31 Vue.js