python备份mysql数据库的实现代码

发布时间:2019-09-28编辑:脚本学堂
分享一例python代码,使用python编程备份mysql数据库,有需要的朋友参考下吧。

python备份mysql/ target=_blank class=infotextkey>mysql数据库的代码,分享给大家。
代码:
 

复制代码 代码示例:
#!/usr/bin/python
#coding=utf-8
#python实现备份mysql数据库,学习python操作mysql数据库的方法
#
'''
@description: backup mysql zabbix databse
@date:2013-08-07
@ower:sunfuxing
'''
import os
import time
mysql_comm = r'/usr/local/mysql/bin/mysqldump'
mysql_user = 'zabbix'
mysql_passwd = 'zabbix'
mysql_bak_database = 'zabbix'
bak_dir = '/root/backup/'
log_file = open('/root/backup/mysql_zabbix.log','a')
today = time.strftime('%Y-%m-%d')
while True:
    if os.path.exists(bak_dir):
        bak_shell = '{0} -u{1} -p{2} {3} >{4}{5}.sql'.format(mysql_comm,mysql_user,
        mysql_passwd,mysql_bak_database,bak_dir,mysql_bak_database)
        tgzfile = 'tar -zcvf {0}{1}.{2}.tar.gz  {3}{4}.sql 1>/dev/null 2>/dev/null'
        .format(bak_dir,mysql_bak_database,today,bak_dir,mysql_bak_database)
        rm_file = 'rm -rf {0}{1}.sql'.format(bak_dir,mysql_bak_database)
        os.system(bak_shell)
        os.system(tgzfile)
        os.system(rm_file)
        print >>log_file,'{0} backup database sucess .....!'.format(today)
        break
    elif not os.path.exists(bak_dir):
        os.mkdir(bak_dir)
        print >>log_file,'backup dirctory create sucess.....!n'
    else:
        print >>log_file,'{0} backup database bad......!'.format(today)
log_file.close()