【问题标题】:Bash script sends email even when it shouldn't即使不应该发送电子邮件,Bash 脚本也会发送
【发布时间】:2017-05-03 02:23:48
【问题描述】:

我有一个由 root 每小时运行的 cron 作业,检查是否存在绊线违规。它仍然每小时给我发一封电子邮件,不管我有没有违规行为。如果存在违规行为,则包括报告。如果没有违规,它会向我发送一封只有主题行的空白电子邮件。

这是脚本:

#!/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`" user@example.com < /tmp/twreport
fi

【问题讨论】:

  • 如果发送的是空白邮件,这似乎表明/tmp/twreport 是空的。这肯定会导致v 被设置为零。建议您调试实际写入该文件的内容。
  • 文件被写入 - 它显示 0 次违规或 x 次违规。 v 是 0 或 1。当我手动运行它时它工作正常,只有在 cron 中它不起作用。
  • 终端和 cron 作业之间的环境存在巨大差异,因此这可能是这里的问题。参见例如stackoverflow.com/questions/1972690/…
  • 啊,脚本中没有tripwire 的完整路径。我已经把它添加进去了,看看它是否执行

标签: bash email debian-jessie tripwire


【解决方案1】:

我建议将代码更改为

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)" user@example.com < /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

【讨论】:

    【解决方案2】:

    尝试用双引号括起来并使用完整路径

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

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

    如果这些都不起作用,请验证搜索词。我在 'found: 0' 上看到 0 前有两个空格

    【讨论】:

    • " 引号的使用在这里不是问题,因为grep -c 总是输出一个数字(没有空格或其他奇怪的东西可以用引号解决)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2010-10-17
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    相关资源
    最近更新 更多