28. 脚本:MySQL服务检测
3.4 mysql监控脚本¶
1.本地端口监控
netstat -tunlp |grep mysql |wc -l
ss -tunlp |grep mysql |wc -l
lsof -i tcp:3306 |wc -l
2.远程端口监控
yum install telnet nmap nc -y
nmap 127.0.0.1 -p 3306 |grep open |wc -l
echo -e "\n" |telnet 127.0.0.1 3306 2>/dev/null|grep Connected |wc -l
3.服务进程监控
ps -ef |grep mysql |grep -v grep |wc -l
4.通过编程语言连接MySQL监控
php连接MySQL
yum install php -mysqlnd php -y
vim mysql_connect.php
<?php
$mysql_id=mysql_connect("localhost","root","123456") or mysql_error();
if ($mysql_id){
echo "connect success..."
}else{
echo mysql_error();
}
php mysql_connect.php
python连接mysql
yum install python3 phthon3-devel phthon3-pip -y
pip3 install pymysql
vim python_mysql_connect.py
import pymysql
db=pymysql.connectP(
host="localhost",
port=3306,
user="root",
password="123456",
db="mysql",
charset="utf8"
)
cursor=db.cursor()
cursor.execute("select version()")
data=cursor.fetchone()
print("mysql connect successfully,the version is %s"%data)
db.close()
python3 python_mysql_connect.py
5.登录MySQL数据库执行语句判断
mysql -uroot -p123456 -e"select version();" &>/dev/null
echo $?
脚本开发
vim mysql_test.sh
#!/bin/bash
echo "-----------------method 1-----------------"
if [ `netstat -tunlp|grep mysql|wc -l` = "1" ];then
echo "mysql is running..."
else
echo "mysql is stopped,now trying to restart mysqld..."
systemctl start mariadb
fi
echo "-----------------method 2----------------------"
if [ `ss -tunlp |grep mysql | wc -l` -eq "1" ];then
echo "mysql is running..."
else
echo "mysql is stopped,now trying to restart mysqld..."
systemctl start mariadb
fi
echo "-----------------method 3----------------------"
if [ `lsof -i tcp:3306 |wc -l` -gt "0" ];then
echo "mysql is running..."
else
echo "mysql is stopped,now trying to restart mysqld..."
systemctl start mariadb
fi
# 使用php测试
echo "-----------------method 4----------------------"
php /myscripts/mysql_connect.php
if [ "$?" -eq 0 ];then
echo "mysql is running..."
else
echo "mysql is stopped,now trying to restart mysqld..."
systemctl start mariadb
fi
# 使用python测试!
echo "-----------------method 5----------------------"
python /myscripts/python_mysql_connect.py
if [ "$?" -eq 0 ];then
echo "mysql is running..."
else
echo "mysql is stopped,now trying to restart mysqld..."
systemctl start mariadb
fi
最后更新:
2022-02-19 13:59:07