python show slave status

时间:2024-05-26 15:37:26

#!/usr/bin/env python

import MySQLdb
import contextlib

@contextlib.contextmanager
def mysql(Host,Port,User,Password,Database):

conn = MySQLdb.connect(host=Host, port=Port, user=User, passwd=Password, db=Database)
#cursor = conn.cursor()
cursor = conn.cursor(MySQLdb.cursors.DictCursor);

try:
yield cursor;
finally:
conn.commit();
cursor.close();
conn.close();

def execSql(excelSql):
hosts = {0:{"host":"192.168.1.140","port":3306,"user":"root","Password":"123456","database":"test"},
1:{"host":"192.168.1.141","port":3306,"user":"root","Password":"123456","database":"test"}}
for idx in hosts:
#print(hosts[idx]["host"])
ip = hosts[idx]["host"]
port = hosts[idx]["port"]
user = hosts[idx]["user"]
password = hosts[idx]["Password"]
database = hosts[idx]["database"]
with mysql(ip,port,user,password,database) as cursor:
sql = excelSql
cursor.execute(sql)
rows = cursor.fetchall()
if len(rows)>0:
Master_Host = rows[0]["Master_Host"]
SQL_THREAD = rows[0]["Slave_SQL_Running"]
IO_THREAD = rows[0]["Slave_IO_Running"]
LAST_ERROR= rows[0]["Last_Error"]
Slave_SQL_RunStatus= rows[0]["Slave_SQL_Running_State"]
Master_InforStatus = rows[0]["Master_Info_File"]
print("-------DataServer:%s------" % ip)
print("relp Master Host: %s" % Master_Host)
print("repl SQL Thread: %s" % SQL_THREAD)
print("repl IO Thread: %s" % IO_THREAD)
print("Mrepl Last error: %s" % LAST_ERROR)
print("Slave SQLRunStatus: %s" % Slave_SQL_RunStatus)
print("Master_InfoStatus: %s" % Master_InforStatus)
print("\n")

if __name__ == "__main__":
sql = "show slave status"
execSql(sql)