Write the script to check remote host services run

2019-03-06 14:40发布

This question already has an answer here:

This is the script but output is wrong even Apache is running its show stop. I'm using 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

标签: bash shell
4条回答
2楼-- · 2019-03-06 15:21

Since ssh returns with exit status of the remote command check man page for ssh and search for exit status

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

查看更多
Evening l夕情丶
3楼-- · 2019-03-06 15:24

First of all httpd is not available in ubuntu. For ubuntu apache2 is available.

So this command ps aux | grep [h]ttpd will not work on ubuntu.

No need to write any script to check the apache status. From ubuntu terminal run this command to get the status:

sudo service apache2 status

Output will be:

A > if apache is running: Apache2 is running (pid 1234)

B > if apache is not running: Apache2 is NOT running.

查看更多
家丑人穷心不美
4楼-- · 2019-03-06 15:30

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.

查看更多
三岁会撩人
5楼-- · 2019-03-06 15:31

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_SUCCESS and EXIT_FAILURE too ( Will be usefull to extend this script in future, if you need ).

But ONE ADVICE : Is better to put the script as a remote process to run with a sudoer user over ssh account

查看更多
登录 后发表回答