tags:

views:

76

answers:

3

I am trying to cut down the number of ports printed in this list:

A.B.C.D 80,280,443,515,631,7627,9100,14000

to the ones that are most interesting for me:

A.B.C.D 80,515,9100

To do this, I am using this bit of code:

foreach (@ips_sorted) {
  print "$_\t";
  my $hostz = $np->get_host($_);
    my $port = 0;
    my $output = 0;
    $port = $hostz->tcp_ports('open');
  if ($port == 80 || $port == 445 || $port == 515 || $port == 9100) {
    $output =  join ',' ,$port;  
  } 
  print $output;

  print "\n";
}

I probably don't need to say, that it's not working. I get this:

A.B.C.D 0

Use of uninitialized value $port in numeric eq (==) at parse-nmap-xml.pl line **(line with if).

+5  A: 

Most likely, the expression $hostz->tcp_ports('open') returned undef, not a number like you expected.

daxim
I added right before the if if ($port != undef) {Now it says Use of uninitialized value in numeric ne (!=) at parse-nmap-xml.pl line 67.
Samantha
Use `if (defined $port)` instead.
Roman Cheplyaka
Thanks Roman, no more uninitialized errors :pbut now I get an empty list! Just like this:A.B.C.D 0
Samantha
Samantha, this is a different problem now. Please [open a new question](http://stackoverflow.com/questions/ask), and post there some more code to aid debugging; the methods `get_host` and `tcp_ports` are interesting, and the content of `@ips_sorted`/some example data is needed.
daxim
Ok Daxim Thanks!
Samantha
+1  A: 

Here is how one can select the interesting ports from a string containing the list of ports:

#!/usr/bin/perl

my %interesting = map { $_ => undef } qw( 80 445 515 9100 );
(undef, my $str) = split ' ', q{A.B.C.D 80,280,443,515,631,7627,9100,14000};

my @ports = grep { exists $interesting{$_} } split /,/, $str;

print "Interesting ports: [@ports]\n";

Here is how I would re-write your code:

#!/usr/bin/perl

my %interesting = map { $_ => undef } qw( 80 445 515 9100 );

for my $ip (@ips_sorted) {
    print "$ip\t";
    my $hostz = $np->get_host($ip);
    unless ( defined $hostz ) {
        warn "get_host returned undef for ip: '$ip'\n";
        next;
    }
    my $port = $hostz->tcp_ports('open');

    unless ( defined $port ) {
        warn "tcp_ports returned undef for ip: '$ip'\n";
        next;
    }

    (undef, my $str) = split ' ', $port;
    my @ports = grep { exists $interesting{$_} } split /,/, $str;

    if ( @ports ) {
        print join(',', @ports);
    }
    print "\n"
}
Sinan Ünür
+1  A: 

$hostz->tcp_ports('open') probably returns a list of ports which you should store in an array variable: @ports instead of $ports. Then you should check each element of the array.

You can do it also in just one line:

$output = join(',', grep { $_ != 80 && $_ != 445 && $_ != 515 && $_ != 9100 } $hostz->tcp_ports('open'));
dolmen