#!/usr/bin/perl -w
#Description: check is_host_alive and is_host_port_open
#Author: donghao
#Date: 2008-05-15
use strict;
use IO::Socket::INET;
use Net::Ping;
# Global Variable
my $Start_pt = $ARGV[1];
my $End_pt = $ARGV[2];
my @ip_net;
#ReadMe
sub Usage(){
print "Note:\n";
print "perl scan_port.pl Ipaddr_File Start_Port End_Port\n";
print "For example: perl scan_port.pl Filename 1 10000\n";
print "Note:The file contains single ip address(192.168.1.2)";
print " or ip network(192.168.1.1-192.168.1.254)\n";
print "Good Luck!\n"
}
#Is_ip_network_or_single_ip
sub Is_ip_nk{
if($_[0] =~ /(^\d+)\.(\d+)\.(\d+)\.(\d+)-(\d+)\.(\d+)\.(\d+)\.(\d+$)/){
for(my $var=$4;$var<=$8;$var++){
&Is_ip_correct($1,$2,$3,$var);
push @ip_net,"$1\.$2\.$3\.$var";
}
return 1;
}
return 0;
}
#Is_Host_Alive or Dead
sub Is_Host_Alive{
my $tmp_syn=Net::Ping->new("syn");
$tmp_syn->ping($_[0]);
if(!$tmp_syn->ack){
printf "The Host %-15s was dead!\n",$_[0];
$tmp_syn->close;
return 0;
}
$tmp_syn->close;
return 1;
}
#Is_Host_Port_Open or Close
sub Is_pt_open{
for(my $tmp_port=$Start_pt;$tmp_port <= $End_pt;$tmp_port++){
my $mysock = IO::Socket::INET->new(PeerAddr => $_[0],
PeerPort => $tmp_port,
Proto => 'tcp') or next;
printf "The host %-15s Port %-8s is opening!\n",$_[0],$tmp_port;
$mysock->close;
}
}
#Is_ip_address_correct or Incorrect
sub Is_ip_correct{
foreach my $num(@_){
next if($num > 0 && $num < 255);
print "The Ip Address is not correct,Check your file!\n";
exit;
}
}
#Main Function
if(! defined $ARGV[0]){
&Usage();
exit 0;
}
open r_ip_addr,"$ARGV[0]" or die "open $ARGV[0] error!\n";
while(<r_ip_addr>){
chomp;
#Ip_Network_Range
if(&Is_ip_nk($_)){
foreach my $Ip_nt_addr(@ip_net){
#check a host for reachability
next if(!&Is_Host_Alive($Ip_nt_addr));
&Is_pt_open($Ip_nt_addr);
}
next;
}
#Single_IpAddress
if(!/(^\d+)\.(\d+)\.(\d+)\.(\d+)/){
&Usage();
exit 0;
}else{
&Is_ip_correct($1,$2,$3,$4);
my $Ip_addr = $_;
#check a host for reachability
next if(!&Is_Host_Alive($Ip_addr));
#check the status of a host's port:close or open
&Is_pt_open($Ip_addr);
}
}
|