Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/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
You can’t perform that action at this time.