不灭的焱

革命尚未成功,同志仍须努力

作者:php-note.com  发布于:2014-03-02 11:14  分类:系统设计/架构  编辑

Python 代码:

#coding=utf-8
#!/usr/bin/python

import os
import time
import zipfile

db_host = 'localhost'
db_user = 'root'
db_pass = '#$$123456'
db_name = 'ty4564ky'
db_charset = 'utf8'

file_name = db_name + '_' + time.strftime('%Y%m%d%H%M') + '.sql'
file_path = '/var/www/html/crontab_python/db/' + file_name

zip_src = file_path
zip_dest = zip_src + '.zip'

back_cmd = '/usr/local/mysql/bin/mysqldump'


def back_db():
	os.system(back_cmd + " -h'%s' -u'%s' -p'%s' '%s' --default_character-set=%s > %s" % (db_host, db_user, db_pass, db_name, db_charset, file_path))


def zip_files():
	f = zipfile.ZipFile(zip_dest, 'w', zipfile.ZIP_DEFLATED)
	f.write(zip_src, file_name)
	f.close()

if __name__ == '__main__':
	print('begin to dump mysql database...')
	back_db()
	print('begin zip files...')
	zip_files()
	print('done, Python is great!')

 

设定定时任务(每天晚上23点整开始备份)

0 23 * * * python /var/www/html/crontab_python/back_db.py >/dev/null 2>&1

 

 

延伸阅读:

Linux 定时任务 Crontab命令 详解