Python : 检查MySQL服务主从同步状态
#!/bin/python2.7 # -*- coding: UTF-8 -*- #coding:utf-8 # created by : caiweicheng import sys #reload(sys) #sys.setdefaultencoding('utf8') from os import popen as get # login-path 配置方式详情 : http://mp.weixin.qq.com/s?timestamp=1519973776&src=3&ver=1&signature=r1Tda4MrTdJ0iWRMCJWpqtPM0GaqsbFN0C8NM7JgQBmJQ9MfAmk7EkUvpJac7l*Rt5znamIiMt-1eJ7K7**-ugTcPz7bNRsI0ND0r3q1rBwR299sxvD5gA8chHGLKF9ZtPZcA0rcVxFptc9Yzzf1N5nrb*JE4EgEntznwUf34hc= # 对比如下信息 是否符合规定 # Master_Log_File == Relay_Master_Log_File # Read_Master_Log_Pos == Exec_Master_Log_Pos # Slave_IO_Running == Yes # Slave_SQL_Running == Yes # 状态码描述 status : { 0:OK , 1 : WARN , 2 :CRITICAL , 3: UNKOWN } def main(login_path) : result=get("mysql --login-path=%s -e 'show slave status \G'"%(login_path)).read().split("\n") slave_status = {} for row in result : # print row # row = row.strip() if ":" not in row : continue k , v = row.split(":" ,1) k = k.strip() v = v.strip() # print( "key is " , k , "value is " , v) slave_status[k]=v status = 3 try : if slave_status["Master_Log_File"] == slave_status["Relay_Master_Log_File"] and slave_status["Read_Master_Log_Pos"] == slave_status["Exec_Master_Log_Pos"] and slave_status["Slave_IO_Running"] == "Yes" and slave_status["Slave_SQL_Running"] == "Yes" : # OK status = 0 elif slave_status["Slave_IO_Running"] != "Yes" and slave_status["Slave_SQL_Running"] != "Yes" : # replace slave Error status = 2 elif slave_status["Master_Log_File"] == slave_status["Relay_Master_Log_File"] and slave_status["Read_Master_Log_Pos"] != slave_status["Exec_Master_Log_Pos"] and slave_status["Slave_IO_Running"] == "Yes" and slave_status["Slave_SQL_Running"] == "Yes" : if int(slave_status["Read_Master_Log_Pos"]) < int(slave_status["Exec_Master_Log_Pos"])+10000 : # OK status = 0 else : #Slow_Exec_Master_Log status = 1 elif slave_status["Master_Log_File"] != slave_status["Relay_Master_Log_File"] : #Slow_Exec_Master_Log status = 2 except : pass return status if __name__ == '__main__': print main( sys.argv[1] )
前提条件:
1: 命令 python \ mysql \ mysql_config_editor
2. 运行方式 python check_MySQL_slavestatus.py login_path
login_path 为必填项目