2014-04-24 198 views

回答

1

您沒有在遠程主機上運行命令。

試試這個。

if ssh -qn [email protected] ps aux | grep -q httpd; then 
    echo "Apache is running" 
else 
    echo "Apache is not running" 
fi 

只要是明確的,ps aux是參數ssh,因此這是被遠程主機上執行了什麼。 grep作爲本地腳本的子節點運行。

+1

同意與sudoer用戶運行。另外,爲了檢查服務是否正在運行,我寧願使用'/etc/init.d/httpd status | grep pid'而不是'ps aux | grep -q httpd' – yejinxin

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.

0

由於ssh以遠程命令的退出狀態返回檢查ssh的手冊頁並搜索退出狀態

所以它的那樣簡單

ssh [email protected] "/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的這個

+0

顯式檢查'$?'是一個反模式。 「if」和朋友的目的恰恰是運行命令並檢查其退出狀態。寫這個的慣用方式就是'if ssh root @ ip「/etc/init.d/apache2 status」;那麼......(這裏的引用實際上是可選的)。 – tripleee

2

嘗試以下操作:

if ssh -qn [email protected] pidof httpd &>/dev/null ; then 
    echo "Apache is running"; 
    exit 0; 
else 
    echo "Apache is not running"; 
    exit 1; 
fi 

這些exit命令將發送正確的EXIT_SUCCESSEXIT_FAILURE(如果需要,將來可以使用此擴展腳本)。

只有一個忠告:最好把腳本作爲遠程過程通過SSH賬號

相關問題