Bash脚本发送电子邮件,即使它不应该

问题描述:

我有一个按root运行的cron作业,每小时检查一次是否存在tripwire违例。无论我是否违规,它每小时都会发送一封电子邮件给我。如果存在违规行为,则包括该报告。如果没有违规行为,它会向我发送一封空白电子邮件,其中只有主题行。Bash脚本发送电子邮件,即使它不应该

这里的脚本:

#!/bin/bash 

# Save report 
tripwire --check > /tmp/twreport 

# Count violations 
v=`grep -c 'Total violations found: 0' /tmp/twreport` 

# Send report 
if [ "$v" -eq 0 ]; then 
     mail -s "[tripwire] Report for `uname -n`" [email protected] < /tmp/twreport 
fi 
+1

如果它发送空白电子邮件,似乎表示'/ tmp/twreport'为空。这肯定会导致'v'被设置为零。建议您调试实际写入该文件的内容。 – paxdiablo

+0

该文件被写入 - 它显示0次违规或x次违规。 v是0或1.当我手动运行它时,它工作正常,只有在cron中不起作用。 – MarkH

+0

终端和cron工作之间的环境差异很大,所以这可能是问题。看例如http://stackoverflow.com/questions/1972690/cannot-get-php-cron-script-to-run/1972763#1972763 – paxdiablo

我建议改变代码

if [ -f /tmp/twreport ] # Check file exists 
then 
v=$(grep -c '^Total violations found: 0$' /tmp/twreport) 
#Not suggested using legacy backticks 
if [ "$v" -eq 0 ]; then 
     mail -s "[tripwire] Report for $(uname -n)" [email protected] < /tmp/twreport 
fi 
fi 

你把脚本行前最后设置在cron路径。像

# Setting PATH 
PATH=/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/path/to/tripwire:/and/so/on 
# Now,set up the cron-job for the script 
0  11   *    *   0  /path/to/script 

尝试用双引号包围,并使用完整路径

v="`/bin/grep -c 'Total violations found: 0' /tmp/twreport`" 

if [ "$v" == "0" ]; then # or = instead of == based on your shell 

如果这些不工作验证搜索词。我在'0'前发现了两个空格'found:0'

+0

'''引号的使用在这里不是问题,因为'grep -c'总是输出一个数字(不包含空格或引用可以修复的其他奇怪的东西)。 – paxdiablo