腳本功能:
成都創(chuàng)新互聯(lián)公司是一家專注于網(wǎng)站制作、做網(wǎng)站與策劃設(shè)計,龍泉網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10多年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:龍泉等地區(qū)。龍泉做網(wǎng)站價格咨詢:028-86922220
1.自動創(chuàng)建備份目錄
2.自動備份數(shù)據(jù)庫的每個表,并壓縮
3.備份結(jié)果,郵件通知聯(lián)系人
4.腳本內(nèi)容
#!/usr/bin/env python # --*-- coding:UTF-8 --*-- # Create by JIANGLEI.YU on 2016/04/21 # 多表自動備份ok。發(fā)送郵件失敗。 import MySQLdb import sys import os import datetime import smtplib from email.mime.text import MIMEText import sys # Define Mysql Environments Hostname='192.168.0.141' Username='root' Password='123456' Database='virtual' MYSQLDUMP='/usr/bin/mysqldump' GZIP='/usr/bin/gzip' timestamp=datetime.datetime.now().strftime("%Y%m%d%H%M%S") Destination_dir='/home/bak/tables/' + timestamp + '/' # Define Smtp Environments Host='smtp.exmail.qq.com' Port=25 sender='yujianglei@singulax.com' Pass='123456' recivers='jianglei.yu@foxmail.com' def main(): if os.path.exists(Destination_dir) == False: os.makedirs(Destination_dir) db_table_backup() else: db_table_backup() def email(): try: server= smtplib.SMTP() server.connect(Host,Port) server.login(sender,Pass) server.sendmail(sender,recivers,msg.as_string()) except Exception,e: print e print "郵件發(fā)送失?。? def backup_failed(): global msg msg = MIMEText('數(shù)據(jù)庫單表備份失敗') msg['subject'] = '數(shù)據(jù)庫單表備份失敗' msg['From'] = sender msg['To'] = recivers email() sys.exit(2) def backup_sucess(): global msg msg = MIMEText(('數(shù)據(jù)庫單表備份成功,共備份%d張表,共用時%.2f分鐘.') % (tables_count,backup_period) , 'plain','utf-8' ) msg['subject'] = '數(shù)據(jù)庫單表備份成功' msg['From'] = sender msg['To'] = recivers email() def db_table_backup(): start_time=datetime.datetime.now() try: db = MySQLdb.connect(Hostname,Username,Password,Database,connect_timeout=2) cursor = db.cursor() except Exception, e: # print e print "連接數(shù)據(jù)庫失敗" backup_failed() cursor.execute('show tables') f = cursor.fetchall() list_status = [] for table in f: # print table for i in table: MYSQLDUMP_CMD = MYSQLDUMP + ' -h' + Hostname + ' -u' + Username + ' -p' + Password + ' ' + Database + ' ' + i + ' ' + '| ' + GZIP + ' >' + Destination_dir + Database + '-' + timestamp+ '.' + i + '.' + 'sql.gz' result = os.system(MYSQLDUMP_CMD) list_status.append(result) global tables_count tables_count = len(list_status) list_test=[0] j = set(list_status).issubset(set(list_test)) if j == True: end_time=datetime.datetime.now() global backup_period backup_period = ((end_time - start_time).seconds)/60.0 backup_sucess() else: backup_failed() cursor.close() db.close() if __name__ == '__main__': main()