[Perl]建立自己的全球ip地址归属地数据库~
时间:2005-09-08 来源:huhuegg
Perl真是好东东!本来用shell处理一天的东西20秒就搞定了
1 从以下网址获取需要处理的全球ip地址归属: http://210.73.64.88/doorway/cgi-bin/getiplist.asp?PageNum=1&PageLine=175000&qtype=0
2 用Perl格式化输出获取的内容(乍一看格式很简单很好处理,小心哦~ 想取出完整内容还不方便呢~)
#!/usr/bin/perl
use URI::Escape;
use DBI;
my $dsn="DBI:mysql:dbname:192.168.1.1";
my $db_user="mysql";
my $db_pass="mysql";
$dbh=DBI->connect($dsn,$db_user,$db_pass,{RaiseError=>1});
my $string;
open (GETIPLIST, "getiplist.txt") || die "$!";
while (<GETIPLIST>) {
chomp $_;
$string=$string . $_;
}
close(GETIPLIST);
$string=~tr/ / /;
$string=~tr/ /#/;
$string=~tr/*//;
$string=~tr/g'/g/;
#print("$string ");
$search="#";
$local=index($string, $search, 0);
$length=1;
open (GETIPLIST1, ">getiplist.1") || die "$!";
while ($length > 0) {
$local1=index($string,$search,$local+1);
$length=$local1-$local;
$text=substr($string, $local+1, $length-1);
if("$text" ne "*") {
$text=substr($string, $local+1, $length-1);
print GETIPLIST1 $text, " ";
}
$local=$local1;
}
close(GETIPLIST1);
print("getiplist.1 write ok! ");
open (GETIPLIST1, "getiplist.1") || die "$!";
open (GETIPLIST2, ">getiplist.2") || die "$!";
$number=1;
while (<GETIPLIST1>) {
chomp $_;
if ($number == $_) {
print GETIPLIST2 " ", $number, "#";
$number=$number+1;
} else {
print GETIPLIST2 $_, "#";
}
}
close(GETIPLIST1);
close(GETIPLIST2);
open (GETIPLIST2, "getiplist.2") || die "$!";
open (GETIPLIST3, ">getiplist.3") || die "$!";
while (<GETIPLIST2>) {
chomp $_;
$numbers=tr/#//;
if ($numbers >= 6) {
@words=split(/#/, $_);
($a, $b, $c ,$d, $e, $f)=@words;
$ee=$e . " " . $f;
# $str=$a . "#" . $b . "#" . $c . "#" . $d . "#" . $ee . "#";
$str=$a . "#" . $b . "#" . $c . "#" . $d . "#" . $ee;
print GETIPLIST3 $str, " ";
} elsif ($numbers == 4) {
# print GETIPLIST3 $_, "Empty", "# ";
print GETIPLIST3 $_, "Empty", " ";
} else {
print GETIPLIST3 substr($_, 0, -1), " ";
}
}
close(GETIPLIST2);
close(GETIPLIST3);
open (GETIPLIST3, "getiplist.3") || die "$!";
while (<GETIPLIST3>) {
chomp $_;
@output=split(/#/, $_);
($out1, $out2, $out3, $out4, $out5)=@output;
$sth=$dbh->prepare("insert into iptable(id,ipfrom,ipto,area1,area2) values('$out1','$out2','$out3','$out4','$out5')");
$sth->execute();
}
close(GETIPLIST3);
$dbh->disconnect();