我尝试使用bash脚本实现以下步骤:
1)检查Apache Server
的状态。
2)如果它已启动并运行,则不执行任何操作。如果不是,请转到步骤3.
3)如果服务器未运行,请先发送失败的电子邮件,然后重新启动服务器
4)重新启动后,再次检查状态,并发送确认电子邮件
这是我的代码:
#checking if Apache is running or not
ps auxw | grep apache2 | grep -v grep > /dev/null
if [ $? != 0 ]
then
mailx -s "Apache web server is down, Trying auto-restart" -$
# web server down, restart the server
sudo /etc/init.d/apache2 restart > /dev/null
sleep 10
#checking if apache restarted or not -- This is not working
ps auxw | grep apache2 | grep -v grep > /dev/null
if [ $? = 0 ]
then
mailx -s "Apache restarted succesfully" -r "$SENDEREMAIL" "$NOTIFYEMAIL" < /$
else
mailx -s "Restart Failed, try restarting manually" -r "$SENDEREMAIL" "$NOTIFYEMAIL" <$
fi
fi
代码正常工作直到第3步,并且在步骤4中失败/不工作,即脚本无法在重新启动并发送确认电子邮件后检查服务器的状态。 有人可以让我知道我哪里出错了。
答案 0 :(得分:2)
试试这个:
#checking if Apache is running or not
if ! pidof apache2 > /dev/null
then
mailx -s "Apache web server is down, Trying auto-restart"
# web server down, restart the server
sudo /etc/init.d/apache2 restart > /dev/null
sleep 10
#checking if apache restarted or not
if pidof apache2 > /dev/null
then
message="Apache restarted successfully"
else
message="Restart Failed, try restarting manually"
fi
mailx -s "$message" -r "$SENDEREMAIL" "$NOTIFYEMAIL"
fi
注意:每个 mailx 行都有一个尾随-$
,< /$
或<$
- 这些似乎是拼写错误并被删除。