程式原理:
透過 twnic 網站所提供的國家網段資訊下來分析
並換算遮罩,最後用 iptables 阻擋
code:
#!/usr/bin/perl -w
use strict;
use LWP::Simple;
my $url = "http://trace.twnic.net.tw/ipstats/ipv4net.php?ipv4_cc=CN&ipv4_country=CHINA&ccountry=%A4%A4%B0%EA%A4j%B3%B0";
my $file = "/tmp/chinaIp.html";
my $status = getstore($url, $file);
die "error $status on $url" unless is_success($status);
my $counter = 0;
my @IPlists;
open(FH,"< /tmp/chinaIp.html") or die "can't open file: $!";
while() {
# 去除不是next if $_ !~ /^
#過濾HTML標籤
s/\<[^\<]+\>//g;
#利用$counter計算並取出第2,3行的資料並存到陣列
$counter++;
if( ($counter == 2) or ($counter == 3) ) {
push(@IPlists, $_);
} elsif( $counter == 5) {
$counter = 0;
}
}
close(FH);
my $i;
for($i=0; $i<$#IPlists; $i+=2){
chomp($IPlists[$i]);
system("/sbin/iptables -A INPUT -p tcp -s " . $IPlists[$i] . '/' . &ConvertMask($IPlists[$i+1]) . " --dport 80 -j DROP");
}
#轉換成遮罩
sub ConvertMask {
my $input = shift;
chomp($input);
return 32 - (log($input) / log(2));
}
沒有留言:
張貼留言