hostsを変更するPHPスクリプト
このような需要があって、私は多くのウェブサイトが異なっている時に異なっているipに対応することを望んで、もし1つ1つ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
書き終わってみると、一度で置き換えを探すだけで済む仕事なのに