bash 编写脚本来检查远程主机服务是否运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23260855/
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
Write the script to check remote host services running or not
提问by user3567376
This is the script but output is wrong even Apache is running its show stop. I'm using Ubuntu 12.04.
这是脚本,但即使 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
回答by ivspenna
Try the following:
请尝试以下操作:
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
These exit
commands will send the correct EXIT_SUCCESSand EXIT_FAILUREtoo ( Will be usefull to extend this script in future, if you need ).
这些exit
命令也将发送正确的EXIT_SUCCESS和EXIT_FAILURE(如果需要,将来扩展此脚本会很有用)。
But ONE ADVICE : Is better to put the script as a remote process to run with a sudoer user over ssh account
但是一个建议:最好将脚本作为远程进程与 sudoer 用户通过 ssh 帐户一起运行
回答by tripleee
You are not running the commands on the remote host.
您没有在远程主机上运行命令。
Try this instead.
试试这个。
if ssh -qn root@ip ps aux | grep -q httpd; then
echo "Apache is running"
else
echo "Apache is not running"
fi
Just to be explicit, ps aux
is the argument to ssh
and so that is what is being executed on the remote host. The grep
runs as a child of the local script.
明确地说,ps aux
是 的参数ssh
,因此这就是在远程主机上执行的内容。在grep
运行作为本地脚本的孩子。
回答by Shanki
First of all httpd is not available in ubuntu. For ubuntu apache2 is available.
首先,httpd 在 ubuntu 中不可用。对于 ubuntu apache2 可用。
So this command ps aux | grep [h]ttpd
will not work on ubuntu.
所以这个命令ps aux | grep [h]ttpd
在 ubuntu 上不起作用。
No need to write any script to check the apache status. From ubuntu terminal run this command to get the status:
无需编写任何脚本来检查 apache 状态。从 ubuntu 终端运行此命令以获取状态:
sudo service apache2 status
Output will be:
输出将是:
A > if apache is running: Apache2 is running (pid 1234)
A > 如果 apache 正在运行: Apache2 is running (pid 1234)
B > if apache is not running: Apache2 is NOT running.
B > 如果 apache 没有运行: Apache2 is NOT running.
回答by PradyJord
Since ssh returns with exit status of the remote commandcheck man page for ssh and search for exit status
由于ssh 以远程命令的退出状态返回,请检查 ssh 的手册页并搜索退出状态
so Its as simple as
所以它很简单
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
You do not need ps or grep for this
为此,您不需要 ps 或 grep