打算在跳板機(jī)上寫(xiě)一個(gè)shell腳本,批量檢查遠(yuǎn)程服務(wù)器上的main進(jìn)程是否在健康運(yùn)行中。
10年積累的成都做網(wǎng)站、成都網(wǎng)站建設(shè)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站策劃后付款的網(wǎng)站建設(shè)流程,更有蒼溪免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
先找出其中一臺(tái)遠(yuǎn)程機(jī)器,查看main進(jìn)程運(yùn)行情況
[root@two002 tmp]# ps -ef|grep main root 23448 23422 0 11:40 pts/0 00:00:00 grep --color=auto main [root@two002 tmp]# ps -ef|grep main|grep -v grep|wc -l
shell檢查腳本如下
[root@two002 tmp]# cat /tmp/main_check.sh #!/bin/bash NUM=$(ps -ef|grep main|grep -v grep|wc -l) if [ $NUM -eq 0 ];then echo "It's not good! main is stoped!" else echo "Don't worry! main is running!" fi
執(zhí)行腳本
[root@two002 tmp]# sh -x /tmp/main_check.sh ++ grep main ++ grep -v grep ++ wc -l ++ ps -ef + NUM=2 + '[' 2 -eq 0 ']' + echo 'Don'\''t worry! main is running!' Don't worry! main is running! [root@two002 tmp]# sh /tmp/main_check.sh Don't worry! main is running!
如上執(zhí)行結(jié)果,發(fā)現(xiàn)腳本執(zhí)行過(guò)程中,看到賦予NUM參數(shù)的結(jié)果值是2!但是手動(dòng)執(zhí)行ps -ef|grep main|grep -v grep|wc -l的結(jié)果明明是0!!
這是由于grep匹配的問(wèn)題,需要grep進(jìn)行精準(zhǔn)匹配,即"grep -w"。這就需要將main_check.sh腳本內(nèi)容修改如下:
[root@two002 tmp]# cat /tmp/main_check.sh #!/bin/bash NUM=$(ps -ef|grep -w main|grep -v grep|wc -l) if [ $NUM -eq 0 ];then echo "Oh!My God! It's broken! main is stoped!" else echo "Don't worry! main is running!" fi
再次執(zhí)行檢查腳本,就OK了
[root@two002 tmp]# sh -x /tmp/main_check.sh ++ grep -w main ++ grep -v grep ++ wc -l ++ ps -ef + NUM=0 + '[' 0 -eq 0 ']' + echo 'Oh!My God! It'\''s broken! main is stoped!' Oh!My God! It's broken! main is stoped! [root@two002 tmp]# sh /tmp/main_check.sh Oh!My God! It's broken! main is stoped!
故在跳板機(jī)上,批量檢查遠(yuǎn)程服務(wù)器的main進(jìn)程運(yùn)行狀態(tài)的腳本為:
[root@tiaoban ~]# cat /usr/bin/main_check #!/bin/bash NUM=$(ps -ef|grep -w main|grep -v grep|wc -l) if [ $NUM -eq 0 ];then echo "Oh!My God! It's broken! main is stoped!" else echo "Don't worry! main is running!" fi [root@tiaoban ~]# cat /opt/script/main_check.sh #!/bin/bash for i in $(cat /opt/ip.list) do /usr/bin/rsync -e "ssh -p22" -avpgolr /usr/bin/main_check $i:/usr/bin/ > /dev/null 2>&1 ssh -p22 root@$i "echo $i;sh /usr/bin/main_check" done