cronjob with email not working - bash

update:
when I echo $res in the script below, I get the following, I guess it's because the script itself contains the word searchd!! so at the very instant that the cronjob process gets executed, $res becomes empty!
I renamed the script, problem solved!
root 10769 7177 0 23:31 pts/1 00:00:00 /bin/bash /home/scripts/monitor_searchd.sh root 10770 10769 0 23:31 pts/1 00:00:00 /bin/bash /home/scripts/monitor_searchd.sh
original problem:
I have a shell script that works when I invoke it in the shell, but when putting in crontab in the following way, it doesn't work(not sending an email). The strange thing is that cron log shows that the process is getting ran every minute!
*/1 * * * * root /home/scripts/monitor_searchd.sh
here's the script:
process="java"
res="`ps -ef|grep $process|grep -v grep`"
if [ ! -n "$res" ]; then
echo "$process is down!" | mail -s "$process is down" xxx#gmail.com
fi
cron log
CROND[7370]: (root) CMD (/home/scripts/monitor_searchd.sh)

Can you please add:
echo "$process is down!" >> /tmp/monitor_searcd.log
before the line with mail? It could help localize the problem.
And pair of small remarks:
Please add
#!/bin/bash
to the first line of the script.
Change
[ ! -n "$res" ]
to
[ -z "$res" ]

Related

Email not send in the cron job shell script

I have this cron job entry:
0 0 * * * /application-data/sendUrl.sh
/application-data/sendUrl.sh has this code:
auditFile="/application-data/auditUrl.txt"
[ -e $auditFile ] && (echo -e "Subject: Foo\nTo: user#example.com\n\n" `cat $auditFile` | sendmail -t ; rm -f $auditFile )
The shell script has all root privileges and correct file permissions. Running it from the command line it sends the email. Only when it's executed by the cron job the email is not sent, but the file at the end of the command list is deleted so I know the shell script has been executed.
Any idea what am I doing wrong so the email is not sent when running as cron job?
Your script doesn't have a shebang so it'll be executed with sh; echo -e behavior is implementation defined with sh
Also, you're deleting the file even if sendmail fails; you should at least test the return status before doing the deletion.
Does it work better like this?
#!/bin/sh
auditFile="/application-data/auditUrl.txt"
[ -f "$auditFile" ] || exit
printf 'Subject: %s\nTo: %s\n\n' "Foo" "user#example.com" |
cat - "$auditFile" |
sendmail -t &&
rm -f "$auditFile"

Cron + nohup = script in cron cannot find command?

There is a simple cron job:
#reboot /home/user/scripts/run.sh > /dev/null 2>&1
run.sh starts a binary (simple web server):
#!/usr/bin/env bash
NPID=/home/user/server/websrv
if [ ! -f $NPID ]
then
echo "Not started"
echo "Starting"
nohup home/user/server/websrv &> my_script.out &
else
NUM=$(ps ax | grep $(cat $NPID) | grep -v grep | wc -l)
if [ $NUM -lt 1 ]
then
echo "Not working"
echo "Starting"
nohup home/user/server/websrv &> my_script.out &
else
ps ax | grep $(cat $NPID) | grep -v grep
echo "All Ok"
fi
fi
websrv gets JSON from user, and runs work.sh script itselves.
The problem is that sh script, which is invoked by websrv, "does not see" commands and stops with exit 1.
The script work.sh is like this:
#!/bin/sh -e
if [ "$#" -ne 1 ]; then
echo "Usage: $0 INPUT"
exit 1
fi
cd $(dirname $0) #good!
pwd #good!
IN="$1"
echo $IN #good!
KEYFORGIT="/some/path"
eval `ssh-agent -s` #good!
which ssh-add #good! (returns /usr/bin/ssh-add)
ssh-add $KEYFORGIT/openssh #error: exit 1!
git pull #error: exit 1!
cd $(dirname $0) #good!
rm -f somefile #error: exit 1!
#############==========Etc.==============
Usage of the full paths does not help.
If the script has been executed itself, it works.
If run.sh manually, it also works.
If I run the command nohup home/user/server/websrv & if works as well.
However, if all this chain of tools is started by cron on boot, work.sh is not able to perform any command except of cp, pwd, which, etc. But invoke of ssh-add, git, cp, rm, make etc., forces exit 1 status of the script. Why it "does not see" the commands? Unfortunately, I also cannot get any extended log which might explain the particular errors.
Try adding the path from the session that runs the script correctly to the cron entry (or inside the script)
Get the current path (where the script runs fine) with echo $PATH and add that to the crontab: replacing the string below with the output -> <REPLACE_WITH_OUTPUT_FROM_ABOVE>
#reboot export PATH=$PATH:<REPLACE_WITH_OUTPUT_FROM_ABOVE>; /home/user/scripts/run.sh > /dev/null 2>&1
You can compare paths with a cron entry like this to see what cron's PATH is:
* * * * * echo $PATH > /tmp/crons_path
Then cat /tmp/crons_path to see what it says.
Example output:
$ crontab -l | grep -v \#
* * * * * echo $PATH >> /tmp/crons_path
# wait a minute or so...
$ cat /tmp/crons_path
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
$ echo $PATH
/home/ubuntu/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
As the commenter above mentioned, crontab doesn't always use the same path as user so likely something is missing.
Be sure to remove the temp cron entry after testing (crontab -e, etc.)...

shell script - run list of commands

for i in `cat foo.txt`
do
$i
done
And I have a input file "foo.txt", with list of commands.
ls -ltr | tail
ps -ef | tail
mysql -e STATUS | grep "^Uptime"
when I run the shell script, it executes, but splits the commands in each line at spaces i.e for first line it executes only "ls", then "-ltr" for which I get command not found error.
How can I run each list as one command?
why am I doing this?
I execute lot of arbitrary shell commands including DB commands. I need to have a error handling as I execute each command(each line from foo.txt), I can't think of what can go wrong, so the idea is put all commands in order and call them in loop and check for error (#?) at each line and stop on error.
Why not just do this?
set -e
. ./foo.txt
set -e causes the shell script to abort if a command exits with a non-zero exit code, and . ./foo.txt executes commands from foo.txt in the current shell.
but I guess I can't send notification (email).
Sure you can. Just run the script in a subshell, and then respond to the result code:
#!/bin/sh
(
set -e
. ./foo.txt
)
if [ "$?" -ne 0 ]; then
echo "The world is on fire!" | mail -s 'Doom is upon us' you#youremail.com
fi
Code mentioned.
for i in `cat foo.txt`
do
$i
done
Please use https://www.shellcheck.net/
This will result _
$ shellcheck myscript
Line 1:
for i in `cat foo.txt`
^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang.
^-- SC2013: To read lines rather than words, pipe/redirect to a 'while read' loop.
^-- SC2006: Use $(...) notation instead of legacy backticked `...`.
Did you mean: (apply this, apply all SC2006)
for i in $(cat foo.txt)
$
Will try while loop, and for test purpose content of foo.txt mentioned below
cat foo.txt
ls -l /tmp/test
ABC
pwd
while read -r line; do $line; if [ "$?" -ne 0 ]; then echo "Send email Notification stating $line Command reported error "; fi; done < foo.txt
total 0
-rw-r--r--. 1 root root 0 Dec 24 11:41 test.txt
bash: ABC: command not found...
Send email Notification stating ABC Command reported error
/tmp
In case error reported you can break the loop.
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_05.html
while read -r line; do $line; if [ "$?" -ne 0 ]; then echo "Send email Notification stating $line Command reported error "; break; fi; done < foo.txt
total 0
-rw-r--r--. 1 root root 0 Dec 24 11:41 test.txt
bash: ABC: command not found...
Send email Notification stating ABC Command reported error
while read -r line; do eval $line; if [ "$?" -ne 0 ]; then echo "Send email Notification stating $line Command reported error "; break; fi; done < foo.txt
total 0
-rw-r--r--. 1 root root 0 Dec 24 11:41 test.txt
bash: ABC: command not found...
Send email Notification stating ABC Command reported error

cronjob not executing script as expected

I have this script running on a Juniper router which essentially is running Freebsd 10. Problem i am facing is the when cronjob is running this script variable ($current_mem) doesn't show any value as a result logger is also not able to log that value. Anyone have any clue what is going on.
#!/bin/bash
localpid=$$
renice -n +1 $localpid &
current_mem="test"
echo "$current_mem" <<<<shows right value
current_mem=$(cli -c "show task memory" | grep "Currently In Use" | awk
'{print $5}' | grep -o '[0-9]*')
echo "$current_mem" <<<<<<<<<<"when cron is running it show's nothing"
if [ "$current_mem" -gt "65" ]
then
echo "$current_mem" <<<<<"shows nothing"
logger -t JTASK_OS_MEM_HIGH -p "external.notice" "Using more then 65
percent of available memory Current utilization:$current_mem" <<<<<
else
echo "$current_mem"
logger -t JTASK_OS_MEM_NORMAL -p "external.notice" "Using less then 65
percent of available memory Current utilization: $current_mem"
fi
When i run this script with sh task_mem.sh, script works perfectly but when i run it through cron it doesn't show/dump the value of variable. This what i have for the cron job
# crontab -l
*/1 * * * * sh /var/tmp/task_mem.sh >>
/var/tmp/task_mem_cron.log
#GordonDavisson that was it "cli" was in /usr/sbin/cli not in /bin as a result cron was not able to execute it. Once i added the full path it started working. Thank you so much for your help

Simple daemon process in Ubuntu

I want to start a simple daemon process in Ubuntu, which will write the current time to log file every 5 seconds.
start-stop-daemon --start --user root --make-pidfile --pidfile /home/manjesh/test.pid --exec /home/manjesh/simplescript.sh
simplescript.sh
#!/bin/bash
echo $(date)" SNMP Monitoring and Log aggregator service " >> /home/manjesh/log.txt
while true
do
echo $(date) >> /home/dcae/snmp-service/log
sleep 5
done
When I execute the command it says "No such file or directory even if the file do exist"
Any help will be appreciated. Thanks.
The way I would do this is to use a cron job that triggers every minute and calls a script that writes the time every 5 seconds, like this:
Cron:
* * * * * /usr/local/bin/script >/dev/null 2>&1
Script:
#!/bin/bash
mkdir -p /home/dcae/snmp-service/
i="0"
while [ $i -lt 12 ]
do
echo $(date) >> /home/dcae/snmp-service/log
i=$[$i+1]
sleep 5
done
The problem was I had created a file in Windows and moved to Ubuntu, and there was a formatting problem
-bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory

Resources