【python自动化运维】paramiko和smtplib模块:检查MySQL从库主从同步状态、备份情况并发送邮件通知

#!/usr/bin/python3
#author 老板你再这样我要删库了
#Mark:2018/9/20初稿

import paramiko
import time
import smtplib
from email.mime.text import MIMEText


time1=time.strftime("%H%M%S")
time2=time.strftime("%y/%m/%d-%H:%M:%S")
time3=time.strftime("%d")

ssh_hostname='##从库IP'
ssh_username='##ssh登录账号'

##已做免密码登录处理,ssh-copy-id
sshc1=paramiko.SSHClient()
sshc1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshc1.connect(hostname=ssh_hostname,username=ssh_username)


def sendmail(mail_content,mail_subject):
	smtp_server="##发件邮件服务器"
	smtp_user="##发件邮箱账号"
	smtp_password="##发件邮箱密码"

	from_mail="##发件人"
	to_mail="##收件人"

	message1=MIMEText(mail_content,'plain','utf-8')
	message1['From']=from_mail
	message1['To']=to_mail
	message1['Cc']="##抄送人"
	message1['Subject']=mail_subject

	smtp1=smtplib.SMTP(smtp_server,'25')
	smtp1.login(smtp_user,smtp_password)

	smtp1.sendmail(from_mail,to_mail,message1.as_string())
	smtp1.close()


##凌晨2点判断备份是否正常
if time1=="020000": 
	stdin,stdout,stderr=sshc1.exec_command('ls -lah /backup/data/|tail -n 1')    ##查看备份路径下文件情况
	backup1=stdout.read().decode(encoding='utf-8',errors='ignore').split()
	file_size=backup1[4]
	file_time=backup1[6]
	file_name=backup1[8]


	mail_content="检查时间:"+time2+"\n\n"+"最新数据库文件:\n\n"+file_name+" ("+file_size+"GB)"

	if file_time==time3:
		mail_subject="车贷系统生产数据库备份成功"
	else:
		mail_subject="车贷系统生产数据库备份失败"

	sendmail(mail_content,mail_subject)

##查看主从同步状态
else:
	stdin, stdout, stderr = sshc1.exec_command('mysql -u##备份账号 -p##账号密码 -e"show slave status\G"')
	slave_s=stdout.read().decode(encoding='utf-8',errors='ignore').replace(' ','').split('\n')

	if slave_s[11] != "Slave_IO_Running:Yes" or slave_s[12] != "Slave_SQL_Running:Yes":
		mail_content="检查时间:"+time2+"\n\n"+"Slave status:\n"+slave_s[11]+"\n"+slave_s[12]+"\n\n"+slave_s[38]
		mail_subject="车贷生产从库异常"
		sendmail(mail_content,mail_subject)

sshc1.close()

 

你可能感兴趣的:(Python自动化运维)