user2193480
user2193480

Reputation: 81

Perl suppress backtick output with ping

Suppressing system output from Perl code.

This code works fine functionally until I run into a hostname that can't resolved and want to suppress the output of a unresolvable domain.

If in the lists.hosts file there is a domain that can't be resolved, the screen output will contain: "ping: cannot resolve XXX.com: Unknown host"

my $ip;

open(HOSTLIST, "lists.hosts");    # Load domains
@hosts = <HOSTLIST>;
chomp($host);

foreach $host (@hosts) {

  $results = `ping -c 1 $host`;

  $record++;

  my $pos = index($results, $find);

  if (($results =~ /ttl=/) || ($results =~ /data bytes/)) {
    #$count++;
    chomp($host);
    if (($results =~ /(?<=bytes from)(.*)(?=:)/) != 0) {
      ($ip) = ($results =~ /(?<=bytes from)(.*)(?=:)/);
    }
    elsif (($results =~ /(?<=\()(.*)(?=\))/) != 0) {
      ($ip) = ($results =~ /(?<=\()(.*)(?=\))/);
    }

    print "Record: $record Host: $host IP:$ip Status: Passed";
    print "\n";

    #print ("*** Record# $record: Ping Test Succeeded for Server: $host ***\n");
    #print ("$results\n");
  }
  else {
    $count++;
    chomp($host);

    #print ("*** Record# $record: Ping Test Failed for Server: $host ***\n");
    print "Record: $record Host: $host Status: Failed\n";

    #print ("$results\n");
  }
}

close(HOSTLIST);

exit($errorcode);

Upvotes: 0

Views: 440

Answers (1)

Andy Lester
Andy Lester

Reputation: 93765

Your invocation of ping needs to capture stderr:

ping -c 1 $host 2>&1

Also, you're not checking the return of your open, which you should do always. Finally, you should be using use warnings; and use strict; at the top.

Upvotes: 1

Related Questions