标签:测试 字符串 进程 定时 str nbsp wget 通过 负载高
在工作中,我们往往利用脚本定时监控本地、远端数据库服务端或Web服务是否运行正常,例如:负载高、cup高、连接数满了等....
方法一:根据端口
本地:netstat/ss/lsof
① netstat –lntup|grep 3306|wc –l
② ss –lntup|grep 3306|wc -l
③ lsof –I :3306|grep mysql|wc –l
远程:telnet/nmap/nc
①echo -e "\n"|telnet baidu.com 80|grep Connected|wc
②namp www.baidu.com -p 80|grep open|wc-l
方法二:根据进程
ps -ef|grep mysql|wc -l
wget/curl (http方式,判断根据返回值或返回内容)
header(http)根据状态码判断
数据库特有,通过mysql客户端连接,根据返回值或返回内存判断。
测试:以mysql为例(端口)
本地:
vim bqh.sh
#!/bin/sh
if [ `lsof -i tcp:3306|wc -l` -gt 0 ]
then
echo "MySQL is Running."
else
echo "MySQL is Stopped."
/etc/init.d/mysqld start
echo "MySQL is Starting......"
fi
执行脚本后效果如下:
当然我们还可以用其它命令方法检测:
[root@lamp01 scripts]# vim bqh.sh
#!/bin/sh
#if [ `lsof -i tcp:3306|wc -l` -gt 0 ]
#if [ `ps -ef|grep mysql|grep -v grep|wc -l` -gt 0 ] #注意脚本名字不能带mysql,自己也算进程
#if [ `netstat -lntup|grep mysql|wc -l` -gt 0 ]
if [ "`netstat -lnt|grep 3306|awk -F "[ :]+" ‘{print $5}‘`" = "3306" ]
then
echo "MySQL is Running."
else
echo "MySQL is Stopped."
/etc/init.d/mysqld start
echo "MySQL is Starting......"
fi
注意:
如果mysql没启动,空值-eq 3306 会报错,如果以字符串的方式比较不会。
远程:
脚本如下:
vim jkmysql.sh
#!/bin/sh #remote #if [ `nc -w 2 192.168.43.118 3306 &>/null&&echo ok|wc -l` -gt 0 ] if [ `nmap 192.168.43.118 -p 3306 2>/dev/null|grep open|wc -l` -gt 0 ] then echo "MySQL is Running..." else echo "MySQL is Stopped." ssh -p22 root@192.168.43.118 "/etc/init.d/mysqld start" #此处需要做免密交互远程登录执行命令,https://www.cnblogs.com/su-root/p/10128237.html echo "MySQL is Starting......" fi
我们在192.168.43.117机器上执行上面的脚本:
我们现在在192.168.43.118机器上把mysql服务关闭,然后再在192.168.43.117机器上执行脚本:
==========================华丽的分割线=================================
测试:以web为例
首先我们先启动nginx服务:
[root@lamp01 scripts]# /application/nginx/sbin/nginx
[root@lamp01 scripts]# curl -I -s www.jyw1.com|head -1
HTTP/1.1 200 OK
[root@lamp01 scripts]# curl -I www.jyw1.com 2>/dev/null |head -1
HTTP/1.1 200 OK
[root@lamp01 scripts]#
curl -I -s www.jyw1.com|head -1 等价于 curl -I www.jyw1.com 2>/dev/null |head -1
脚本如下:
vim web.sh
#!bin/sh
if [ `curl -I -s www.jyw1.com|head -1|egrep "200"|wc -l` -eq 1 ]
then
echo "httpd is Running..."
else
echo "httpd is Stopped!"
/application/nginx/sbin/nginx
echo "please wait..."
echo "httpd is Runing......"
fi
当然我们还可以用其它命令方法检测:
脚本如下:
#!/bin/sh if [ "`curl -s www.jyw1.com &>/dev/null&&echo $?`" = "0" ] then echo "Httpd is Running..." else echo "Httpd is Stoped..." /application/nginx/sbin/nginx echo "please wait..." echo "httpd is Runing......" fi
标签:测试 字符串 进程 定时 str nbsp wget 通过 负载高
原文地址:https://www.cnblogs.com/su-root/p/10409973.html