LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Ping device or device2 and log it to a file with timestamp (https://www.linuxquestions.org/questions/linux-newbie-8/ping-device-or-device2-and-log-it-to-a-file-with-timestamp-4175603779/)

ran4keli 04-13-2017 11:12 AM

Ping device or device2 and log it to a file with timestamp
 
I have a server, running Centos 6.2, that runs an app that is dependent on a stratus0 timeserver. I need to verify connectivity with a timeserver prior to starting NTPD and the app.
I am currently using the following cmd to accomplish this:
until /bin/ping -c 1 timeserver1 >> /var/log/ntpd.log || /bin/ping -c 1 timeserver2 >> /var/log/ntpd.log ; do
sleep 2
done

The only problem is that I cannot determine the timestamp for the log entries. I have attempted using the following cmd:
/bin/ping -c 1 timeserver1 | xargs -n1 -i bash -c 'echo `date +%F\ %T`" {}"' >> /var/log/ntpd.log || /bin/ping -c 1 timeserver2 | xargs -n1 -i bash -c 'echo `date +%F\ %T`" {}"' >> /var/log/ntpd.log ; do
sleep 2
done

The problem with this is if timserver1 is offline, it only logs the ping failure to timeserver1 and does not perform the or (||) and look for timeserver2.

If this is the wrong forum, please enlighten me and I will post it in the correct forum.

Thank you for your assistance.

jpollard 04-13-2017 05:00 PM

It has been a while...

Try putting () around the first command with the pipe. The opening "(" would go before the first ping command. The ")" would go just before the ||

If I remember right, the shell waits for the second command for the exit status and it may be losing the ping exit.

michaelk 04-13-2017 08:02 PM

Probably not the most efficient. I didn't check your xargs statement.

Code:

ping -c 1 timeserver1 | xargs -n1 -i bash -c 'echo `date +%F\ %T`" {}"' >> /var/log/ntpd.log
a=$?
ping -c 1 timerserver2 | xargs -n1 -i bash -c 'echo `date +%F\ %T`" {}"' >> /var/log/ntpd.log
b=$?
until [[ $a -ne 1 || $b -ne 1 ]]
do
  sleep 2
  ping -c 1 timerserver1 | xargs -n1 -i bash -c 'echo `date +%F\ %T`" {}"' >> /var/log/ntpd.log
  a=$?
  ping -c 1 timerserver2 | xargs -n1 -i bash -c 'echo `date +%F\ %T`" {}"' >> /var/log/ntpd.log
  b=$?
done



All times are GMT -5. The time now is 03:35 PM.