python备份mysql数据库表_python脚本按表备份MySQL数据库

脚本功能:

1.自动创建备份目录

2.自动备份数据库的每个表,并压缩

3.备份结果,邮件通知联系人

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

4.脚本内容

#!/usr/bin/env  python

# --*-- coding:UTF-8 --*--

# Create by JIANGLEI.YU on 2016/04/21

# 多表自动备份ok。发送邮件失败。

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 "邮件发送失败!"

def backup_failed():

global msg

msg = MIMEText('数据库单表备份失败')

msg['subject'] = '数据库单表备份失败'

msg['From'] = sender

msg['To'] = recivers

email()

sys.exit(2)

def backup_sucess():

global msg

msg = MIMEText(('数据库单表备份成功,共备份%d张表,共用时%.2f分钟.') % (tables_count,backup_period) ,  'plain','utf-8' )

msg['subject'] = '数据库单表备份成功'

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 "连接数据库失败"

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值