【问题标题】:Running bash script in cron在 cron 中运行 bash 脚本
【发布时间】:2014-06-11 01:19:39
【问题描述】:

我有以下 bash 脚本:

!/bin/bash
# script to send simple email 
#Wait 5 seconds
#sleep 05
# email subject
SUBJECT="SUBJECT"
# Email To ?
EMAIL="EMAIL"
# Email text/message
MYIP=$(curl http://ipecho.net/plain)
LASTIP=$(head -n 1 /home/ubuntu/myip.txt)
echo "Last IP:" $LASTIP
echo "Current IP:" $MYIP
#Check if IPs are the same
if [[ "$MYIP" == "$LASTIP" ]]; then
        echo "IP hasn't changed. Do nothing."
else
        sendemail -f $EMAIL -t $EMAIL -u $SUBJECT -m $MYIP -s smtp.gmail.com -o tls=yes -xu username -xp password
        echo $MYIP > myip.txt
fi

当我尝试在命令行中运行它时,它运行良好。当我将它包含在“crontab -e”中时,问题就开始了:“* * * * * /home/ubuntu/myip.sh”。

然后它不起作用。似乎是 sendmail 无法正常运行。 当我执行以下操作时:tail -f /var/log/syslog

Sep 18 21:48:02 gpuserver sendmail[18665]: r8J1m1gO018665: from=ubuntu, size=314, class=0, nrcpts=1, msgid=<201309190148.r8J1m1gO018665@gpuserver>, relay=ubuntu@localhost
Sep 18 21:48:02 gpuserver sendmail[18665]: r8J1m1gO018665: to=ubuntu, ctladdr=ubuntu (1000/1000), delay=00:00:01, xdelay=00:00:00, mailer=relay, pri=30314, relay=[127.0.0.1] [127.0.0.1], dsn=4.0.0, stat=Deferred: Connection refused by [127.0.0.1]

有什么想法吗?

【问题讨论】:

  • 你用的是什么sendmail?
  • sendemail 中的e 是真实脚本中的拼写错误,还是只是此处的复制错误?
  • cron 是否配置为发送 cron 作业的输出?
  • 您是否在.profile.bash_profile.bashrc 中设置了任何影响sendmail 的环境变量? Cron 作业不会运行您的个人资料。
  • sendemail中的e是正确的! (通过 apt-get install sendemail 安装)

标签: linux bash ubuntu cron


【解决方案1】:

当您从命令行运行脚本时,您正在利用当前环境。 Cron 没有这些信息......所以你应该从命令行做的是:

env > me

然后编辑脚本并在脚本开头包含 ./me。这样您的 cron 任务将在相同的环境中运行。

【讨论】:

  • 我想你的意思是. ./me。如果您不使用. 命令,脚本将在子shell 中运行,并且不会在脚本中设置变量。此外,您需要将export 命令添加到所有分配中。
  • 这还有另一个潜在问题:env &gt; me 如果值包含空格,则不会引用它们。
  • 不工作。将 ./me 添加到文件的开头,然后运行 ​​env > me ,仍然显示相同的问题。我觉得它与 root 的 sendmail 配置文件有关。尝试了几种解决方案都没有任何效果(特别是因为 sendemail,它只是一个 sendmail 的脚本)
  • 我想你误解了——你需要做的是先运行 env 命令,在登录时将你的 shell 环境变量的当前设置的副本保存到文件中。/me 然后阅读使用 vim 或您喜欢的文本编辑器将我的内容放入您的 cron 脚本中,以便在您尝试运行 sendmail 之前在脚本中设置所有环境变量
【解决方案2】:

当 cron 将某些内容打印到 stdout 或 stderr 时,cron 本身会尝试通过电子邮件发送报告。由于您可能没有配置系统范围的电子邮件,这可能是 syslog 中的错误消息的来源。

为防止 cron 发送任何邮件,请确保您的脚本及其生成的任何命令不会向 stdout 或 stderr 输出任何内容。一个简单的方法是将“&>/dev/null”添加到您的 cron 行。

您还可以在 crontab 的开头添加 'MAILTO=""'。

这一切都记录在 cron/crontab (man -k cron) 的手册页中。

【讨论】:

    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 2011-08-10
    • 2013-11-26
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 2017-05-28
    • 2016-10-01
    相关资源
    最近更新 更多