#!/usr/bin/perl use strict; use warnings; use Net::DNS; use NetAddr::IP; use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep clock_gettime clock_getres clock_nanosleep clock stat );use DBI; use Math::Round; my $current_range = 0; $SIG{'INT'} = 'CLEANUP'; $SIG{'TERM'} = 'CLEANUP'; sub CLEANUP { print "Caught SIGTERM, marking range $current_range as stopped\n"; if ($current_range != 0) { my $dsn = 'DBI:mysql:reverse_dns:localhost'; my $db_user_name = 'db user'; my $db_password = 'password'; my ($id, $password); my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die("Cannot connect to database"); $dbh->do(qq{update `ranges` set status = 2 ,start_time = 0,session=0 where id = $current_range}); } exit(1); } # now connect to the DB my $dsn = 'DBI:mysql:reverse_dns:localhost'; my $db_user_name = 'db user'; my $db_password = 'none of your business'; my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die("Cannot connect to database"); # get the IP ranges to work on my $query1 = $dbh->prepare('select * from ranges where status = 0 OR status = 2 order by status desc limit 1'); $query1->execute( while (my @ranges = $query1->fetchrow_array()) { my $range_id = $ranges[0]; $current_range = $range_id; my $ip = new NetAddr::IP ($ranges[1].'/'.$ranges[2]) + ($ranges[4] +1) or die "Unable to create IP object\n"; # $ranges[4] is the previous offset my $res = Net::DNS::Resolver->new; my $num = $ip->num(); $res->tcp_timeout(10); $dbh->do(qq{ update ranges set status = 1, start_time = UNIX_TIMESTAMP() where id = $range_id}) or die("Can't set a range to in progress"); my $success = 0; my $errors = 0; print "Starting at ".$ip->addr()."\n"; my $session = 0; for (my $i=$ranges[4]; $i<=$num; ++$i) { my $ip_address = $ip->addr(); if ($ip_address) { my $query = $res->search("$ip_address"); if ($query) { foreach my $rr ($query->answer) { next unless $rr->type eq "PTR"; my $hostname = $rr->ptrdname; $dbh->do( qq{ insert into entries (ip,hostname,time,range_id) values(INET_ATON('$ip_address'),"$hostname",NOW(),$range_id) }); $success++; } } else { $errors++; } $dbh->do(qq{update ranges set offset = $i,session=$session where id = $range_id}); $session++; } if ($i % 100 == 0) { print $ranges[1].'/'.$ranges[2]." ".int((($i/$num)*100))."% Processed $i of $num IPs, Sucessful $success, Failed $errors\n"; } ++$ip; usleep(25); # to stop it overloading the nameserver! } $dbh->do(qq{update ranges set status=3,start_time=0,session=0 where id = $range_id}) or die("Can't set a range to done"); } print "Pass complete!\n";