import os
import sys
import configparser
import time
def test_file_path(fp):
if not os.path.exists(fp):
raise RuntimeError('file {} not found'.format(fp))
def backup_mysqldb(backup_param):
test_file_path(backup_param['mysql']['dump'])
test_file_path(backup_param['bak']['cmd_zip'])
cmd1 = '{dump} -u{user} -p{password} -h{hostip} \
-P{port} {dbname}'.format(**backup_param['mysql'])
print(cmd1)
backup_name = time.strftime('mysqlbackup%Y%m%d_%H%M%S')
backup_param['bak']['backup_name'] = backup_name
cmd2 = backup_param['bak']['cmd_bak'].format(**backup_param['bak'])
print(cmd2)
cmd = cmd1 + ' | ' + cmd2
print(cmd)
os.system(cmd)
def del_old_backup(backup_param):
backup_path = backup_param['bak']['backuppath']
print(int(backup_param['bak']['keepday']))
t = time.time() - int(backup_param['bak']['keepday']) * 24 * 60 * 60
last_day = time.strftime('%Y%m%d', time.localtime(t))
for fn in os.listdir(backup_path):
fp = os.path.join(backup_path, fn)
print(fp)
if os.path.isfile(fp):
file_day = get_time_from_name(fn)
print(file_day, last_day)
if file_day < last_day:
print('del file ', fn)
os.remove(fp)
def get_time_from_name(fn):
# mysqlbackup20140211_172713.7z
import re
pattern = r'.*(\d{8})_\d*'
m = re.match(pattern, fn)
return m.group(1)
if __name__ == '__main__':
current_dir = sys.argv[0]
current_dir = os.path.abspath(current_dir)
current_dir = os.path.dirname(current_dir)
os.chdir(current_dir)
print(os.getcwd())
config = configparser.ConfigParser()
config.read_file(open(current_dir + r'\config.ini'))
for k,v in config.items():
for k1,v1 in v.items():
print('{}\n {}:{}'.format(k, k1, v1))
backup_mysqldb(config)
del_old_backup(config)
配置文件
[mysql]
hostip=localhost
user=root
password=12345
port=3306
dbname=test
dump=path_to_mysqldump.exe
[bak]
cmd_zip=.\7z.exe
cmd_bak={cmd_zip} a {backuppath}\{backup_name}.7z -si{backup_name}.bak
backuppath=.\backup
keepday=7
代码打包