0

I use this script to restart the apache2 web server since the letsencrypt ssl renew process does not restart it once it has finished its actions.

When i test it manually by stoping the server and running the script. It works fine. However when it is part of a cronjob that runs, the webserver does not start. However in the /var/log/syslog i have a lot of lines stating it is trying to start the web server.

Here is the script:

#!/bin/sh

ps auxw | grep '/usr/sbin/apache2' | grep -v grep > /dev/null

if [ $? != 0 ]
then
        logger "starting apache2 - keep-apache2-alive"
        sudo service apache2 start
else
        logger "apache2 is running - keep-apache2-alive"
fi

The crontab entry looks like this, running every 2 minutes.

*/2 * * * * /home/user/scripts/keep-apache-running.sh

The /var/log/syslog entries look like so:

Dec 30 23:34:01 node root: apache2 is running - keep-apache2-alive
Dec 30 23:36:01 node root: apache2 is running - keep-apache2-alive
Dec 30 23:38:01 node root: starting apache2 - keep-apache2-alive
Dec 30 23:40:01 node root: starting apache2 - keep-apache2-alive
Dec 30 23:42:01 node root: starting apache2 - keep-apache2-alive
Dec 30 23:44:01 node root: starting apache2 - keep-apache2-alive
Dec 30 23:46:01 node root: starting apache2 - keep-apache2-alive
Dec 30 23:48:01 node root: starting apache2 - keep-apache2-alive
Dec 30 23:50:01 node root: starting apache2 - keep-apache2-alive

I think I solved it. I looked at root's mail and noticed that cron was reporting that it cannot find the "service" command. So the /usr/sbin was not included in the path. I went in and hardcoded the absolute path to the service command and now it should work.

Thanks.

Dan
  • 173
  • 1
  • 1
  • 7
  • Run it in root's crontab and remove `sudo`. – Piotr P. Karwasz Dec 31 '19 at 20:47
  • @PiotrP.Karwasz thanks for your response. I have used sudo crontab -e to add the cronjob. It should be running as root. Also "root:" is present in the /var/log/syslog file. Before i had the "service" command without sudo and it also did not work. – Dan Dec 31 '19 at 20:56

1 Answers1

0

I think I solved it. I looked at root's mail and noticed that cron was reporting that it cannot find the "service" command. So the /usr/sbin was not included in the PATH. I went in and hardcoded the absolute path to the service command and now it should work.

You can either set the PATH at the top of your shell script or you can hardcode the absolute paths to all commands you are calling from your script.

This was helpful in finding my solution.

https://askubuntu.com/questions/23009/why-crontab-scripts-are-not-working

Dan
  • 173
  • 1
  • 1
  • 7