Home:ALL Converter>schedule a cron job to ping a server and run python script

schedule a cron job to ping a server and run python script

Ask Time:2022-09-05T09:11:57         Author:Tomas Melo Peralta

Json Formatter

I am trying to automate a bash script in Ubuntu. The script pings a server and then runs a python script if the packet is not received. The python script sends me a a notification when the ping is not returned. The script works when I run it manually, but it is not working when I schedule a cron job.

The bash script is named ping.sh.

#!/bin/bash


pingString=$(ping -c 1  google.com) # google is just and example, for my script I am using a server that intentionally does not return the packet.
msgRecieved="1 received, 0% packet loss"
msgLost="0 received, 100% packet loss"


if `echo ${pingString} | grep "${msgLost}" 1>/dev/null 2>&1`
then
  python3 ping.py
fi

This is how I setup the cron job: crontab -u username -e

* * * * * /bin/sh /home/username/Documents/ping.sh

I am confused because I set other dummy cron job for testing and it works fine. Example below:

* * * * * /bin/sh /home/username/Documents/test.sh

test.sh

#! /bin/bash

touch /home/username/Documents/ping_server/text.txt

The text.txt file is successfully created every minute.

Author:Tomas Melo Peralta,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/73603766/schedule-a-cron-job-to-ping-a-server-and-run-python-script
yy