简体   繁体   中英

Check for only open port with perl

I need to write a script to scan ports on server and generate a report. This script should:

Read a list of IPs from a file; Scan each IP, and write a file with the results.

I am using below script for this::

#!/usr/bin/perl -w
use strict;
use IO::Socket::PortState qw(check_ports);

my $hostfile = 'hosts.txt';

my %port_hash = (
        tcp => {
            22      => {},
            443     => {},
            80      => {},
            53      => {},
            30032   => {},
            13720   => {},
            13782   => {},
            }
        );

my $timeout = 5;

open HOSTS, '<', $hostfile or die "Cannot open $hostfile:$!\n";

while (my $host = <HOSTS>) {
    chomp($host);
    my $host_hr = check_ports($host,$timeout,\%port_hash);
    print "Host - $host\n";
    for my $port (sort {$a <=> $b} keys %{$host_hr->{tcp}}) {
        my $yesno = $host_hr->{tcp}{$port}{open} ? "yes" : "no";
        print "$port - $yesno\n";
    }
    print "\n";
}

close HOSTS;

Now I have 1 thing to do with is::

Scan for all open ports.

Currently it is scanning ports %port_hash but I need to scan all the ports and list ports which are open. How to do this?

This will fill up %porthash with all the ports:

my %port_hash = ( tcp => {} );
for my $port (1 .. 65535) {
  $port_hash{'tcp'}{$port} = {};
}

Then you can call check_ports with this %port_hash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM