编写脚本以检查远程主机服务是否正在运行

时间:2014-04-24 05:54:37

标签: bash shell

这是脚本,但即使Apache正在运行show stop,输出也是错误的。我正在使用Ubuntu 12.04。

ssh -qn root@ ip

if ps aux | grep [h]ttpd > /dev/null
then
    echo "Apcache is running"
else
    echo "Apcahe is not running"

fi

4 个答案:

答案 0 :(得分:3)

尝试以下方法:

if ssh -qn root@ip pidof httpd &>/dev/null ; then
     echo "Apache is running";
     exit 0;
else
     echo "Apache is not running";
     exit 1;
fi

这些exit命令也会发送正确的 EXIT_SUCCESS EXIT_FAILURE (如果需要,将来有助于扩展此脚本)。

  
    

但是一个建议:最好将脚本作为远程进程与ssh帐户上的sudoer用户一起运行

  

答案 1 :(得分:1)

您没有在远程主机上运行命令。

试试这个。

if ssh -qn root@ip ps aux | grep -q httpd; then
    echo "Apache is running"
else
    echo "Apache is not running"
fi

为了明确,ps auxssh的参数,因此这是在远程主机上执行的内容。 grep作为本地脚本的子项运行。

答案 2 :(得分:0)

首先,httpd在ubuntu中不可用。对于ubuntu,apache2可用。

所以这个命令ps aux | grep [h]ttpd不适用于ubuntu。

无需编写任何脚本来检查apache状态。从ubuntu终端运行此命令以获取状态:

sudo service apache2 status

输出将是:

A>如果apache正在运行:Apache2 is running (pid 1234)

B>如果apache没有运行:Apache2 is NOT running.

答案 3 :(得分:0)

由于 ssh返回远程命令的退出状态,请检查ssh的手册页并搜索退出状态

所以它就像

一样简单
ssh root@ip "/etc/init.d/apache2 status"
if [ $? -ne 0 ]; then                       # if service is running exit status is 0 for "/etc/init.d/apache2 status"
 echo "Apache is not running"
else 
 echo "Apache is running"
fi

这个

你不需要ps或grep
相关问题