本文已参与「掘力星计划」
通过编程实现获取mysql主从同步的状态信息,结合多线程加快效率
#-*- encoding:utf-8 -*-
import paramiko
import threading
#ssh2为连接到10.1.1.167获取mysql master的log_file和position,并写到一个文件中报存起来
def ssh2(ip,username,passwd,cmd):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,22,username,passwd,timeout=5)
fileWrite=open('out.txt','w')
for m in cmd:
stdin, stdout, stderr = ssh.exec_command(m)
stdin.write("yes") #简单交互
out = stdout.readlines()
if ('' != out):
fileWrite.writelines(out)
fileWrite.close()
print '%s\tOK\n'%(ip)
ssh.close()
except :
print '%s\tError\n'%(ip)
if __name__=='__main__':
cmd=["echo 'show master status\G' |/usr/local/mysql/bin/mysql -uroot -p8h3QEAp9 |egrep -E 'File|Position'|awk '{print $2}'"]
cmd2=["file=`cat ./out.txt|head -1`","num=`cat ./out.txt|grep -v mysql`","echo -e 'slave stop;\nchange master to master_host='10.1.1.167',master_user='rsync',master_password='123456',master_log_file='$file',master_log_pos=$num;"]
cmd3=["echo 'show master status\G' |/usr/local/mysql/bin/mysql -uroot -p8h3QEAp9"]
username = "root" #用户名
passwd = "QHa8695R2KuJ" #密码
threads = [] #多线程
#for i in range(167,169): #如果有多个 ip 可以更改里面的数值
# ip = '10.1.1.'+str(i)
ip='10.1.1.167'
a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
a.start()