Skip to content

Instantly share code, notes, and snippets.

@aero
Created July 22, 2010 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aero/485703 to your computer and use it in GitHub Desktop.
Save aero/485703 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use IO::Socket;
use threads;
use Thread::Queue;
my $count : shared;
my $hostcnt : shared;
my $thrnum : shared = 50; # change to adjust performance
my @host_list : shared;
sub scan {
my ($data) = @_;
my ($host, $port) = split /\s+/, $data;
#print "$host : $port ";
my $sock = new IO::Socket::INET (PeerAddr => $host, PeerPort => $port, Timeout => 1);
if ($sock) {
#print "OK\n";
close $sock;
} else {
#print "CRITICAL\n";
push @host_list, "$host:$port";
}
}
#print " Building queue... \n";
my $q = Thread::Queue->new();
open my $HOSTS, 'port_list.txt' or die $!;
while (<$HOSTS>) {
next if /^#/ || /^\s+$/;
chomp $_;
$q->enqueue($_);
$hostcnt++;
}
close $HOSTS;
#print "Added $hostcnt hosts\n";
#print "$thrnum worker thread(s) will be spawned\n";
#print "Scan initiated for $hostcnt hosts\n";
while (1) {
my @threads = threads->list;
if ($q->pending > 0) {
if ($#threads <= $thrnum + 1) {
threads->new(\&scan, $q->dequeue);
$count++;
} else {
foreach my $running (@threads) {
$running->join();
}
}
#printf " %s hosts scanned\n", $count;
} else {
if ($#threads > 0) {
foreach my $running (@threads) {
$running->join();
}
}
last;
}
}
#print "\nThe following ports closed\n";
if ( @host_list ) {
print "CRITICAL - ";
foreach ( @host_list ) {
print "$_ ";
}
print "closed\n";
exit 2; # Critical
} else {
print "OK - $count ports opened\n";
exit 0; # OK
}
print "UNKNOWN\n";
exit 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment