Adding the effectiveness of my ip blacklist-whitelist script

My script opens two files: whitelist.txt and blacklist.txt, filled with IP addresses.

I want to add all ip instances to blacklist.txt that do not exist in whitelist.txt for the variable.

This script counts up to 2 wildcards.

Now it works after 37 minutes, and I would like it to be faster.

$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"; } } 
+5
source share
1 answer

Does this code do what you need?

 $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); 

It outputs:

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

Source: https://habr.com/ru/post/1206955/


All Articles