Python:MySQL/MariaDB 监控与启动

1、检查 MySQL/MariaDB是否启动

import MySQLdb
import time
import subprocess


def excuteCommand(com):
    ex = subprocess.Popen(com, stdout=subprocess.PIPE, shell=True)
    out, err  = ex.communicate()
    status = ex.wait()
    print("cmd in:", com)
    print("cmd out: ", out.decode())
    return out.decode()


p = subprocess.Popen('netstat -ntlp|grep mysql',shell=True,stdout=subprocess.PIPE)
status = p.stdout.readlines()
print(status)

if not status:
    status = excuteCommand('systemctl start mariadb')

print(status)

2、测试

[root@vultr ~]# netstat -ntlp|grep mysql
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      7694/mysqld
[root@vultr ~]# systemctl stop mariadb
[root@vultr ~]# netstat -ntlp|grep mysql
[root@vultr ~]# lsof -i :3306
[root@vultr ~]# /opt/py3/bin/python /u01/mysql_mon.py
[]
[b'tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      8188/mysqld         \n']
[root@vultr ~]# netstat -ntlp|grep mysql
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      8188/mysqld
[root@vultr ~]# lsof -i :3306
COMMAND  PID  USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
mysqld  8188 mysql   14u  IPv4 4367907      0t0  TCP *:mysql (LISTEN)

3、创建后台监控任务

[root@vultr ~]# crontab -l
*/1 * * * * /opt/py3/bin/python /u01/mysql_mon.py
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注