tags:

views:

330

answers:

4

I want a bash script that'll do:

for c in computers:
do
   ping $c
   if ping is sucessfull:
      ssh $c 'check something'
done

If I only do ssh and the computer is iresponsive, it takes forever for the timeout. So I was thinking of using the output of ping to see if the computer is alive or not. How do I do that? Other ideas will be great also

+1  A: 

Use ping's return value:

for C in computers; do
  ping -q -c 1 $C && ssh $C 'check something'
done

ping will exit with value 0 if that single ping (-c 1) succceeds. On a ping timeout, or if $C cannot be resolved, it will exit with a non-zero value.

Stephan202
A: 

Hi

ping -o

and catch the return code

?

Mark

High Performance Mark
The `ping` I have here doesn't take an `-o` flag...
Stephan202
A: 

I wrote that script some 10 years ago:

http://www.win.tue.nl/~rp/bin/rshall

You probably won't need the part where it determines every reachable host and iterates over each of them.

reinierpost
+1  A: 

Use the -w switch on the ping command, then inspect the command's return value.

ping -w 1 $c
RETVAL=$?
if [ RETVAL -eq 0 ]; then
    ssh $c 'check something'
fi

You may want to adjust the parameter you pass with -w if the hosts you're connecting to are far away and the latency is higher.

From man ping:

   -w deadline
          Specify  a  timeout, in seconds, before ping exits regardless of
          how many packets have been sent or received. In this  case  ping
          does  not  stop after count packet are sent, it waits either for
          deadline expire or until count probes are answered or  for  some
          error notification from network.
Mike Mazur
The line RETVAL=$? doesn't work - I'm new in bash. How do you make it work?
Guy
sorry - my mistake. It works
Guy