bash Cronjob 检查并重新启动服务,如果死了

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34931846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:07:38  来源:igfitidea点击:

Cronjob to check and restart service if dead

linuxbashcentoscrontab

提问by User

I want a 1 liner that can check and restart services, such as Apache if they are inactive/dead.

我想要一个可以检查和重新启动服务的 1 班轮,例如 Apache,如果它们处于非活动状态/死亡状态。

I want to put it in crontab and run it every minute to make sure the service is still running.

我想把它放在 crontab 中并每分钟运行一次以确保服务仍在运行。

回答by NarūnasK

service_ck.sh

service_ck.sh

#!/bin/bash
STATUS=$(/etc/init.d/service_name status)
# Most services will return something like "OK" if they are in fact "OK"
test "$STATUS" = "expected_value" || /etc/init.d/service_name restart

Change file permissions:

更改文件权限:

chmod +x service_ck.sh

Update your crontab:

更新您的 crontab:

# min   hour    day month   dow cmd
*/1 *   *   *   *   /path/to/service_ck.sh

回答by Seva Kobylin

You can use special software like monitfor this case. It can check your daemons , restart it if needed and send you alerts. Another good option -- it can stoptry to restart service after N fails (for example if service cannot start).

monit对于这种情况,您可以使用特殊软件。它可以检查您的守护进程,在需要时重新启动它并向您发送警报。另一个不错的选择——它可以在 N 失败后停止尝试重新启动服务(例如,如果服务无法启动)。

回答by mmccaff

If you save this as a bash script it will be a one-liner that you can call from cron. This will restart Apache if it's not in the process list returned by pgrep.

如果您将其保存为 bash 脚本,它将是您可以从 cron 调用的单行。如果它不在 pgrep 返回的进程列表中,这将重新启动 Apache。

Obviously this assumes that you have pgrep. Adjust your command to restart accordingly.

显然,这假设您有 pgrep。调整您的命令以相应地重新启动。

If Apache is running but not responsive, that is a different issue. You'd have to check that some endpoint is responding (and responding correctly) within a specified timeout, etc.

如果 Apache 正在运行但没有响应,那是另一个问题。您必须检查某个端点是否在指定的超时内响应(并正确响应)等。

#!/bin/bash

RESTART="/etc/init.d/httpd restart"
PGREP="/usr/bin/pgrep"
HTTPD="httpd"

$PGREP ${HTTPD}

if [ $? -ne 0 ] # if apache not running 
then
 # restart apache
 $RESTART
fi