【问题标题】:Bash - start multiple services if any is running CentOS 6.8Bash - 如果有运行 CentOS 6.8 的服务,则启动多个服务
【发布时间】:2019-11-03 02:45:28
【问题描述】:

我想检查一个(或所有)服务是否正在运行,如果是,请停止它

#!/bin/bash


# Define an array of processes to be checked.
# If properly quoted, these may contain spaces

check_process=( "nagios" "httpd" )

for p in "${check_process[@]}"; do
    if pgrep "$p" > /dev/null; then
        echo "Process \`$p' is running, stopping it"
        service $p stop
    else
        echo "Process \`$p' is not running"
    fi
done

对于 httpd 服务一切正常,脚本正确检测 httpd 服务状态。 我在检测nagios 服务状态时遇到问题。 但是虽然nagios 服务没有运行,但脚本显示它正在运行

Process `nagios' is running, stopping it
Stopping nagios:No lock file found in /usr/local/nagios/var/nagios.lock
Process `httpd' is not running

有没有更优雅的方法来检测 nagios 服务是否正在运行而不检查 nagios.lock 文件是否存在?

pgrep nagios 在服务未调整时不显示输出。

【问题讨论】:

  • 使用状态:bash.cyberciti.biz/guide/Service_command#The_status_command。或者直接调用stop,如果已经停止,则什么都不做。
  • Nic3500 所说的,只是现在大多数系统都使用systemd 代替——看看命令systemctl
  • 我使用的是 CentOS 6,那里没有 systemctl
  • 为什么不无条件运行service "$p" stop
  • 如果没有其他帮助,我会这样做

标签: bash shell unix


【解决方案1】:

我放弃了,这对我来说很好:

虽然ps -ef | grep -v grep | grep $service | wc -l 显示 0 表示 nagios,但脚本报告 nagios 服务正在运行

#!/bin/bash

logfile=/tmp/stop_nagios.txt

exec >> $logfile

exec 2>&1


service=httpd

if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then
   echo "$service is running, stopping it"
   date
   sudo service $service stop


else
   echo "$service is not running"

fi

 # check nagios service    

FILE=/usr/local/nagios/var/nagios.lock
if test -f "$FILE"; then
    echo "nagios service is running, stopping it"
    date
    sudo service nagios stop
else
    echo "nagios is not running..."


fi

【讨论】:

    猜你喜欢
    • 2015-11-17
    • 2018-01-25
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多