向大家分享一个shell脚本的坑

打算在跳板机上写一个shell脚本,批量检查远程服务器上的main进程是否在健康运行中。

10年积累的成都做网站、成都网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站策划后付款的网站建设流程,更有苍溪免费网站建设让你可以放心的选择与我们合作。

先找出其中一台远程机器,查看main进程运行情况

[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

执行脚本

[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!

如上执行结果,发现脚本执行过程中,看到赋予NUM参数的结果值是2!但是手动执行ps -ef|grep main|grep -v grep|wc -l的结果明明是0!!
这是由于grep匹配的问题,需要grep进行精准匹配,即"grep -w"。这就需要将main_check.sh脚本内容修改如下:

[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

再次执行检查脚本,就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!

故在跳板机上,批量检查远程服务器的main进程运行状态的脚本为:

[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  

网页标题:向大家分享一个shell脚本的坑
标题网址:http://csruizhi.cn/article/giipid.html

其他资讯

Copyright © 2007-2024 成都优众联杰科技有限公司 All Rights Reserved 蜀ICP备2024116266号
友情链接: 网站制作 成都h5网站建设 营销型网站建设 高端定制网站设计 定制级高端网站建设 上市集团网站建设 成都定制网站建设 营销型网站建设 定制网站制作 成都网站建设 高端网站设计推广 成都网站建设 专业网站设计 成都网站建设公司 网站制作 H5网站制作 外贸营销网站建设 手机网站建设 成都网站建设 重庆网站建设 阿坝网站设计 高端品牌网站建设