python监测mysql,并自动重启

最近一朋友的mysql偶尔宕机,便用python写了个小监测程序
linux中自带python,以及subprocess模块,原理就是分析服务器上service mysql status的返回值进行状态分析

# -*- coding: utf-8 -*- 
import commands
import os
import time
import subprocess
n=1
flag=0
while 1:
    trans_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    #print '当前监测周期------->%s'%n,'当前时间------->%s'%trans_time
    print '当前监测周期--->%s,当前时间--->%s'%(n,trans_time)
    n+=1
    #p = subprocess.Popen('ps -ef|grep mysqld', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    try:
        if flag==0:
            p = subprocess.Popen('service mysqld status', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        else:
            p = subprocess.Popen('service mysql status', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    except Exception,e:
        print 'subprocess1 exception---->%s'%e
        flag=0
        continue
    #result=len(p.stdout.readlines())
    result=''.join(p.stdout.readlines()).strip()
    #if result<=3:
    try:
        if 'stop' in result or 'not' in result:
            if flag==0:
                subprocess.Popen('service mysqld start', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            else:
                subprocess.Popen('service mysql start', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            print '数据库启动中...'
            while True:
                #p1=subprocess.Popen('ps -ef|grep mysqld', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                if flag==0:
                    p1=subprocess.Popen('service mysqld status', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                else:
                    p1=subprocess.Popen('service mysql status', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                #result1=len(p1.stdout.readlines())
                result1=''.join(p1.stdout.readlines()).strip()
                #if result1>3:
                if 'stop' in result1 or 'not' in result1:
                    print 'Current Mysqld Progress No.---%s'%result1
                    time.sleep(1)
                    continue
                else: 'running' in result1:
                    print 'Db Restart Success!----%s'%result1
                    break
                #else:

        elif 'is running' in result or 'running' in result:
            print '数据库状态正常'
            time.sleep(600)
            continue
        elif 'unrecognized' in result:
            print 'unrecognized service try mysql,waiting...'
            flag=1
            p = subprocess.Popen('service mysql status', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            continue
        else:
            print 'unknown error---->%s'%result
            continue
    except Exception,e:
        print 'subprocess2 except for reason %s'%e
        flag=0
        continue

监测mysql是否宕机,并自动重启

猜你喜欢

转载自blog.csdn.net/qq_23279427/article/details/73290438