我写了一个bash脚本,当它挂起并向管理员发送电子邮件时重启Apache。代码如下所示。如果Apache进程的数量为零,代码将重新启动Apache。问题是:Apache有时挂起,进程仍然不为零,所以在这种情况下脚本不会重启Apache。 需要的是:如果挂起并且进程不为零,我如何修改代码以重启Apache。
#!/bin/bash
if [ `pgrep apache2 -c` -le "0" ]; then
/etc/init.d/apache2 stop
pkill -u www-data
/etc/init.d/apache2 start
echo "restarting....."
SUBJECT="Apache auto restart"
# Email To ?
EMAIL="me@mydomain.com"
# Email text/message
EMAILMESSAGE="apache auto restart done"
# send an email using /bin/mail
/bin/mail -s "$SUBJECT" "$EMAIL" "$EMAILMESSAGE"
fi
答案 0 :(得分:32)
我们曾经有时在机器上进行Apache segfaulting;这是我们用来尝试调试问题同时保持Apache的脚本。它每分钟左右从cron(作为root)运行一次。它应该是不言自明的。
#!/bin/sh
# Script that checks whether apache is still up, and if not:
# - e-mail the last bit of log files
# - kick some life back into it
# -- Thomas, 20050606
PATH=/bin:/usr/bin
THEDIR=/tmp/apache-watchdog
EMAIL=yourself@example.com
mkdir -p $THEDIR
if ( wget --timeout=30 -q -P $THEDIR http://localhost/robots.txt )
then
# we are up
touch ~/.apache-was-up
else
# down! but if it was down already, don't keep spamming
if [[ -f ~/.apache-was-up ]]
then
# write a nice e-mail
echo -n "apache crashed at " > $THEDIR/mail
date >> $THEDIR/mail
echo >> $THEDIR/mail
echo "Access log:" >> $THEDIR/mail
tail -n 30 /var/log/apache2_access/current >> $THEDIR/mail
echo >> $THEDIR/mail
echo "Error log:" >> $THEDIR/mail
tail -n 30 /var/log/apache2_error/current >> $THEDIR/mail
echo >> $THEDIR/mail
# kick apache
echo "Now kicking apache..." >> $THEDIR/mail
/etc/init.d/apache2 stop >> $THEDIR/mail 2>&1
killall -9 apache2 >> $THEDIR/mail 2>&1
/etc/init.d/apache2 start >> $THEDIR/mail 2>&1
# send the mail
echo >> $THEDIR/mail
echo "Good luck troubleshooting!" >> $THEDIR/mail
mail -s "apache-watchdog: apache crashed" $EMAIL < $THEDIR/mail
rm ~/.apache-was-up
fi
fi
rm -rf $THEDIR
我们从未弄清楚问题......
答案 1 :(得分:2)
进程计数真的可以小于零吗?
这应该足够了:
if ! pgrep apache2 -c >/dev/null; then
答案 2 :(得分:1)
您可以尝试向apache发送http请求(例如使用wget --timeout=10
),如果该请求超时或失败(退出状态!= 0),则终止并重新启动apache。
答案 3 :(得分:1)
为什么Apache会挂起?你能找到原因吗?
有许多脚本和工具可以“守护”应用程序并监视它们。正如您在Debian或Ubuntu上看到的那样,请查看包daemon
和daemontools
。我相信还有其他人。