cron job executing script not writing to file

I have a server running AIDE, and a cron job that runs executes a bash script and sends an email alert out. It is still a WIP, but I can’t get the script to run properly. When the script is executed, my output file defined here /sbin/aide --check > /tmp/$AIDEOUT is still an empty file. I even tried a simple /bin/echo "hello world" > /tmp/$AIDEOUT and it also doesn’t seem to work. The /tmp/$AIDEOUT file remains empty.

However, if I run this script manually without using Cron, it runs fine.

Here is my bash script

#!/bin/bash

PATH=/sbin:/bin:/usr/sbin:/usr/bin

MYDATE=`date +%Y-%m-%d`
AIDEOUT="AIDE-${MYDATE}.txt"
MAIL_TO=
ALLMATCH='All files match AIDE database. Looks okay!'
MAIL_FROM=

/bin/touch /tmp/$AIDEOUT
/bin/chmod 755 /tmp/$AIDEOUT
#/bin/echo "Aide check `date`" > /tmp/$AIDEOUT
/sbin/aide --check > /tmp/$AIDEOUT

if ! grep -q "$ALLMATCH" /tmp/$AIDEOUT; then
    /usr/bin/mailx -s "Daily AIDE report for $(hostname)-${ENVIRONMENT_NAME} ${AWS_REGION}" -r $MAILFROM $MAILTO  < /tmp/$AIDEOUT
fi

#/bin/rm /tmp/$AIDEOUT

/sbin/aide --update
/usr/bin/mv /var/lib/aide/aide.db.gz /var/lib/aide/db_backup/aide.db.gz-$(date +"%m-%d-%y")
/usr/bin/mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

my cronjob is defined in /etc/cron.d/aide
*/5 * * * * root /usr/local/etc/cron_aide2.sh

Thanks!

Answer

You are using selinux. If you “setenforce 0” and then let cron run, you will get the output you expect. At the root shell, your selinux context is:

unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

But when running from Cron, your selinux context starts as:

system_u:system_r:system_cronjob_t:s0-s0:c0.c1023

The solution is downright silly. Instead of:

/sbin/aide –check > /tmp/$AIDEOUT

use

/sbin/aide –check 2>&1 | cat > /tmp/$AIDEOUT

Attribution
Source : Link , Question Author : popopanda , Answer Author : Bill

Leave a Comment