用PHP处理hosts的脚本

作者:柯冷 发布时间:2011-3-21 11:05 Monday 分类:折腾 18979 人围观

error_reporting(0);

$self = pathinfo(__FILE__);

$self = $argv[0];

$help = <<<_

=========================

作者:HK

博客:http://blog.ohko.cn/

=========================

显示帮助: $self -h

列出hosts: $self -ls

关闭hosts: $self -c xxx.com

开启hosts: $self -o xxx.com

添加hosts: $self -a ip xxx.com comment

添加hosts: $self -d xxx.com

禁止所有hosts: $self -c all

开启所有hosts: $self -o all

_;

if(!isset($argv[1])) die($help);


$file = $_SERVER['SystemRoot'] . '/system32/drivers/etc/hosts';

$file_ = $_SERVER['SystemRoot'] . '/system32/drivers/etc/hosts_back';


// 分析hosts文件

$content = file_get_contents($file);

$array = explode("\r\n", $content);

$ip = array();

$reg = "/^[ ]*(#?)[ ]*([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})[ ]*([^#]*)(#.*)?$/";

foreach($array as $z)

{

preg_match($reg, $z, $out);

if(empty($out)) continue;

$ip[trim($out[3])] = array(

'#' => $out[1]==’#'?’#':’ ‘,

‘ip’ => $out[2],

‘url’ => trim($out[3]),

‘comment’ => isset($out[4])?$out[4]:”,

);

}


// 分析命令

switch($argv[1])

{

case ‘-ls’: doing(0, 1); break;

case ‘-c’: close_open(); break;

case ‘-o’: close_open(); break;

case ‘-a’: add(); break;

case ‘-d’: del(); break;

default: doing(0, 1);

}

// 关闭/打开

function close_open()

{

global $help, $argv, $ip;


if(!isset($argv[2])) die($help);


$c = $argv[1]==’-c’?'#’:’ ‘;

if($argv[2] == ‘all’)

{

foreach($ip as $x=>$y) $ip[$x]['#'] = $c;

}

else

{

if(!isset($ip[$argv[2]])) die(“未找到{$argv[2]}的相关设置”);

$ip[$argv[2]]['#'] = $c;

}


doing(1);

}

// 添加

function add()

{

global $help, $argv, $ip;


if(!isset($argv[3])) die($help);


$ip[$argv[3]] = array(‘#’=>’ ‘, ‘ip’=>$argv[2], ‘url’=>$argv[3], ‘comment’=>isset($argv[4])?$argv[4]:”);


doing(1);

}

// 删除

function del()

{

global $help, $argv, $ip;


if(!isset($argv[2])) die($help);


unset($ip[$argv[2]]);


doing(1);

}


// 处理、显示

function doing($w = false, $ls = false)

{

global $ip, $file, $file_;


if($w)

{

if(!file_exists($file_))

{

copy($file, $file_) || die(“hosts文件备份失败!”);

}

$f = fopen($file, ‘w+’);

if(!$f) die(‘没有权限打开hosts文件!’);

}

foreach($ip as $z)

{

$line = “{$z['#']}{$z['ip']}\t{$z['url']}\t\t{$z['comment']}\r\n”;

if($w) fwrite($f, $line);

if($ls) echo $line;

}

if($w) fclose($f);

}

标签: PHP hosts 脚本

添加新评论 »