脚本功能:
, 1。自动创建备份目录
, 2。自动备份数据库的每个表,并压缩
, 3。备份结果,邮件通知联系人
, 4。脚本内容
# !/usr/bin/env python #,(*),编码:UTF-8 ——* #,Create by  JIANGLEI.YU 提醒2016/04/21 #,多表自动备份好。发送邮件失败。 import MySQLdb import 系统 import 操作系统 import datetime import smtplib 得到,,,email.mime.text , import MIMEText import 系统 #,Define Mysql 环境 主机名=' 192.168.0.141 ' 用户名=案? 密码=' 123456 ' 数据库=靶槟狻? ,MYSQLDUMP='/usr/bin/, MYSQLDUMP ' GZIP=/usr/bin/GZIP的 时间戳=datetime.datetime.now () .strftime (“% Y % m % d % H % m % S”) Destination_dir=?home/贝克/表/?+,timestamp +, '/' #,Define Smtp 环境 主机=' smtp.exmail.qq.com ' 端口=25 发送方=皔ujianglei@singulax.com” 通过=' 123456 ' 接收器=' jianglei.yu@foxmail.com ' def main (): if os.path.exists (Destination_dir),==,错误的: os.makedirs (Destination_dir) db_table_backup () 其他: db_table_backup () def 电子邮件(): 试一试: 服务器=,smtplib.SMTP () server.connect(主机、端口) server.login(发送者,通过) server.sendmail(发送器、接收器,msg.as_string ()) except 例外,e: print e print “邮件发送失败!” def backup_failed (): global 味精 时间=msg MIMEText(“数据库单表备份失败”) 味精(“主题”),=,“数据库单表备份失败的 味精(“的”),=,发送者 味精(','],=,接收器 电子邮件() sys.exit (2) def backup_sucess (): global msg 时间=msg MIMEText((“数据库单表备份成功,共备份% d张表,共用时% .2f分钟。”),%,(tables_count backup_period),,,,“普通”,“utf - 8”,), 味精(“主题”),=,“数据库单表备份成功的,, 味精(“的”),=,发送者 味精(','],=,接收器 电子邮件() def db_table_backup (): start_time=datetime.datetime.now () 试一试: 时间=db MySQLdb.connect(主机名、用户名、密码、数据库、connect_timeout=2) 时间=cursor db.cursor () 例外,except e: #,print e print “连接数据库失败” backup_failed () cursor.execute (“show 表”) 时间=f cursor.fetchall () 时间=list_status [] for table f:拷贝 #,print 表 for 小姐:拷贝表: +=MYSQLDUMP_CMD MYSQLDUMP “, - h”, +, Hostname +,“, - u”, +, Username +,“, - p”, +, Password +,‘,’, +,, Database +,‘,’, +,小姐:+,‘,’,+,|,的,+,GZIP +,“,在”,+,Destination_dir +, Database +,“-”, +, +时间戳,“。”,+,小姐:+,“。”,+,“sql.gz” 时间=result os.system (MYSQLDUMP_CMD) list_status.append(结果) global tables_count tables_count =, len (list_status) list_test=[0]=j 集(list_status) .issubset(设置(list_test)) if j ==,真的: end_time=datetime.datetime.now () global backup_period backup_period =, ((end_time 作用;start_time),接着)/60.0 backup_sucess () 其他: backup_failed () cursor.close () db.close () if __name__ ==,,“__main__”: main ()