LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Need help with a basic script (https://www.linuxquestions.org/questions/programming-9/need-help-with-a-basic-script-459190/)

rsmccain 06-28-2006 01:44 PM

Need help with a basic script
 
I have a text file that has 1 server per line listed in it. I need writting a script that will ping each server and report back if it is up or not.

Any help is appreciated.

Thank You.

MensaWater 06-28-2006 02:12 PM

Code:

for HOST in `cat hostlist`
do
  if ping -c 1 $HOST >/dev/null 2>&1
  then echo "Successfully pinged ${HOST}."
  else echo "ERROR: Unable to ping ${HOST}."
  fi
done

You would substitute the name of your file for "hostlist" above. HOST is an abitrary variable name - it can be anything you want (e.g. SERVER) but remember to change the variable call in the rest of it (e.g. ${SERVER}).

Note that the characters in the first line are back ticks rather than apostrophes.

jonaskoelker 06-28-2006 02:15 PM

You want something like this:
Code:

IFS='
'
for host in $(cat file-of-hosts.txt); do
  if ping $host; then
    echo $host is up
  else
  echo $host is down
  fi
done

Check what the exit status of ping is if the host is up and down, respectively, and what other exit status can occur. Some hosts don't respond to pings, though, so you may get false negatives. You may want to have a look at host, tcptraceroute and (if you want to really get into the nuts and bolts) the ARP protocol.

Also, xargs might be useful as an alternate to the for loop.

rsmccain 06-28-2006 02:30 PM

Thanks!
 
Quote:

Originally Posted by jlightner
Code:

for HOST in `cat hostlist`
do
  if ping -c 1 $HOST >/dev/null 2>&1
  then echo "Successfully pinged ${HOST}."
  else echo "ERROR: Unable to ping ${HOST}."
  fi
done

You would substitute the name of your file for "hostlist" above. HOST is an abitrary variable name - it can be anything you want (e.g. SERVER) but remember to change the variable call in the rest of it (e.g. ${SERVER}).

Note that the characters in the first line are back ticks rather than apostrophes.


Thanks to both of you. It looks so simple, I just haven't gotten my arms around scripting yet!

jonaskoelker 06-29-2006 03:28 AM

Have a look at Advanced Bash Scripting guide, at http://www.tldp.org/LDP/abs/html/.

XavierP 07-03-2006 06:28 AM

Moved: This thread is more suitable in Programming and has been moved accordingly to help your thread/question get the exposure it deserves.


All times are GMT -5. The time now is 09:16 PM.