备份mysql数据库的python脚本,backup.py:
import os
import urllib
import json
import socket
import thread
import urlparse
import time
import shutil
sourcePath = "/Data/mysql/data/db_name"
def delete_file_folder(src):
'''delete files and folders'''
if os.path.isfile(src):
try:
os.remove(src)
except:
pass
elif os.path.isdir(src):
for item in os.listdir(src):
itemsrc=os.path.join(src,item)
delete_file_folder(itemsrc)
try:
os.rmdir(src)
except:
pass
def copy_file_folder(src):
'''copy files'''
for item in os.listdir(sourcePath):
itemsrc=os.path.join(sourcePath,item)
if os.path.isfile(itemsrc):
shutil.copy(itemsrc, src)
def backup():
'''backup mysql'''
now = int(time.time())
yesterday = now - 3600*24
newFilename = time.strftime("%Y-%m-%d", time.localtime(yesterday))
path = "/Data/backup/"
isExists = os.path.exists(path + newFilename)
if not isExists:
try:
os.mkdir(path + newFilename)
copy_file_folder(path + newFilename)
except:
pass
old = yesterday - 2*3600*24
oldFilename = time.strftime("%Y-%m-%d", time.localtime(old))
delete_file_folder(path + oldFilename)
if __name__ == "__main__":
while 1:
htime = int(time.strftime('%H',time.localtime(time.time())))
if htime == 3:
backup()
time.sleep(60)
nohup python backup.py & //启动python脚本,nohup命令进程持久化,该命令可以在你退出帐户/关闭终端之后继续运行相应的进程
ps aux | grep python //查看python进程