Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help writing shell script 1

Status
Not open for further replies.

jonnyknowsbest

Technical User
Feb 3, 2004
163
GB
We are running SCO OpenServer and i need help writing a shell script to do the following:

1) at 23:50, the server should try pinging the network router.
2) if the ping is succesful, the script should retry the ping
3) if at any point the ping is unsuccessful, the script should create a file containing the text "Connectivity lost at " followed by the system time.
4) the script should loop until 1:15
 
Create a shell script similar to this, replacing testhost and /tmp/logfile with appropriate values:

Code:
#!/bin/ksh
i=0
while ping -c1 testhost > /dev/null 2>&1 && (( i < 25 ))
do
        sleep 60
        ((i=i+1))
done
if ((i < 25))
then
        echo Connectivity lost at `date` >> /tmp/logfile
else
        echo Ping test timed out >> /tmp/logfile
fi

It checks ping once a minute for 25 minutes. Obviously you can make it more frequent by reducing the sleep time and increasing the number of iterations.

Let's say it's called /tmp/pingtest. Then add it to cron using crontab -e:

[tt]50 23 * * * /tmp/pingtest[/tt]

Make sure the script is executable by typing chmod 755 /tmp/pingtest.

Annihilannic.
 
Hi

Just as a note between parenthesis. I sucked a lot with [tt]ping[/tt] some weeks ago. Because some unresolvable addresses could make it to hang. For example :
Code:
ping -c1 1.1
( Ok, that one is a malformed IP address, but can hang as well for addresses valid and pingable 3 minutes earlier. )

Appearantly the solution is :
man ping said:
-w deadline
Specify a timeout, in seconds, before ping exits
regardless of how many packets have been sent or
received.
But sadly, not all [tt]ping[/tt] implementations have it.
( The one from iputils-ss020124 is ok, but GNU inetutils 1.4.2 has nothing usefull for this purpose. )

So I wrote a small function for this. ( Provided just as example. )
Code:
function pingw()
{
  ping="ping"
  while [ $# -ne 0 ]; do
    test "$1" == "-w" && { shift; deadline="${1:-1}"; } || ping="$ping $1"
    shift
  done
  $ping &
  pid=$!
  sec=0
  while ps $pid > /dev/null; do
    sleep 1
    test $((++sec)) -ge "0$deadline" && break
  done
  ps $pid > /dev/null && kill -SIGINT $pid
}

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top