Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ping a host with a Perl one-liner with Net::Ping?

Tags:

perl

Trying to integrate the following Perl one-liner into a shell script. This code works within a Perl script but not as a one-liner executed from a shell script.

I've tried replacing $host with a real hostname with no luck.

#!/bin/ksh

hosts="host1 host2 host3"

PERL=/usr/bin/perl

# Check to see if hosts are accessible.
for host in $hosts
do
   #echo $host
   $PERL -e 'use Net::Ping; $timeout=5; $p=Net::Ping->new("icmp", $timeout) or die bye ; print "$host is alive \n" if $p->ping($host); $p->close;'
done
like image 539
XMAN Avatar asked Oct 18 '10 15:10

XMAN


3 Answers

The single quotes in the shell stop the $host from being interpreted. So you can just stop and restart the single quotes as required:

perl -MNet::Ping -e 'if (Net::Ping->new("icmp", 5)->ping("'$host'")) {print "'$host' is alive\n"}'

Alternatively, you can pass the host in as a parameter - see the other answer.

like image 82
a'r Avatar answered Nov 20 '22 20:11

a'r


Try to replace $host:

$PERL -e 'use Net::Ping; $timeout=5; $p=Net::Ping->new("icmp", $timeout) or die bye ; print "$host is alive \n" if $p->ping($host); $p->close;' 

with $ARGV[0], the first command line argument:

$PERL -e 'use Net::Ping; $timeout=5; $p=Net::Ping->new("icmp", $timeout) or die bye ; print "$ARGV[0] is alive \n" if $p->ping($ARGV[0]); $p->close;' $host
like image 24
OMG_peanuts Avatar answered Nov 20 '22 20:11

OMG_peanuts


If you want to use Perl, then use the Perl interpreter to run your script.

#!/usr/bin/env perl -w
use Net::Ping;
$timeout=5;
$p=Net::Ping->new("icmp", $timeout) or die bye ;
@hosts=qw/localhost 10.10.10.10/;
foreach my $host (@hosts) {
  print "$host is alive \n" if $p->ping($host);
}
$p->close;

Otherwise, you might as well use the ping command directly from the shell

#!/bin/bash
for hosts in host1 host2 host3
do
  if ping  ...... "$hosts"  >/dev/null  ;then
      .....
  fi 
done
like image 1
ghostdog74 Avatar answered Nov 20 '22 20:11

ghostdog74