添加效率我的ip blacklist-whitelist脚本

时间:2014-11-15 18:03:25

标签: php algorithm

我的脚本会打开两个文件:whitelist.txt和blacklist.txt,其中包含ip地址。

我想将whitelist.txt中不存在的blacklist.txt中的所有ip实例添加到变量中。

此脚本最多可以包含2个通配符。

现在它的运行时间为37分钟,我希望这会更快。

$blacklist = file_get_contents("blacklist.txt");
$whitelist = file_get_contents("whitelist.txt");

$black_ips = explode("\n", $blacklist);
$white_ips = explode("\n", $whitelist);

$wildcard = array();
for($i = 0; $i < 256; $i++) {
  $wildcard[] = $i;
}

foreach($black_ips as $bkey => $black) {
  if(stristr($black, ".")) {

    foreach ($white_ips as $wkey => $white) {
      $count = substr_count($white, '*');

      if($count) {
        switch($count){
          case 1:
            foreach ($wildcard as $i) {
              if(substr($white, 0, strlen($white) - 1) . $i == $black){
                continue 4;
              }
            }
            break;
          case 2:
            foreach ($wildcard as $i) {
              foreach ($wildcard as $k) {
                if(substr($white, 0, strlen($white) - 3) . $i . '.' . $k == $black){
                  continue 5;
                }
              }
            }
            break;
        }
      }
      else if($black == $white) {
        continue 2;
      }
    }
    $nginxdeny .= "deny " . $black . ";\n";
  }
}

1 个答案:

答案 0 :(得分:3)

此代码是否符合您的要求?

$white = array(
    '192.168.*.*',
    '10.10.10.*',
);

$black = array(
    '192.168.8.8',
    '10.10.10.3',
    '10.10.1.2',
);

$patterns = array();
foreach ($white as $subnetwork) {
    $patterns[] = str_replace(array('.', '*'), array('\\.', '(\d{1,3})'), $subnetwork);
}

$notMatched = array();
foreach ($black as $ip) {
    foreach ($patterns as $pattern) {
        if (preg_match("/^{$pattern}$/", $ip)) {
            continue 2;
        }
    }
    $notMatched[] = $ip;
}

var_dump($notMatched);

输出:

array(1) {
  [0]=>
  string(9) "10.10.1.2"
}