微软 Firefox mysql Android Ubuntu google 开源 linux shell java php apache centos HTML5 Python 程序员 wordpress Windows nginx linux命令

使用python备份VPS上的网站文件及数据库 1.0

学python有一段时间了,花了两天时间写了个备份的脚本。可以将Linux vps上的网站目录及数据库全部导出一份到远程ftp服务器上,再配置crontab实现每天的自动备份。加入了N多自动判断,不会导致程序轻易出错。

代码仅适于python2,不适用于python3。因为调用了压缩模块,还需要yum install zlib zlib-devel

最后,需要强调的,此段代码是个python菜鸟写出来的,还望路过的大侠指点一二,切莫贱笑!

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import zipfile
import socket
import commands
from datetime import date,datetime,timedelta
from ftplib import FTP

########你需要修改的地方开始#########
website_dir='/home/wwwroot'  #你的网站目录
backup_dir='/home/backup'   #本地的备份目录(即要把备份文件放在哪里)
mysql_user='root'    #mysql用户名
mysql_password='xxxxx'   #mysql密码
ftp_server='xx.xx.xx.xx'    #远程FTP服务器地址
ftp_user='xxxxx'    #远程FTP用户名
ftp_password='xxxxx'    #远程FTP密码
ftp_backup_dir='backup'    #远程FTP上要用于备份的目录
########你需要修改的地方结束#########

print("checking backup directory...")
try:
    if os.path.isdir(backup_dir):
        print("found backup directory " + backup_dir + ", ready to process backup...")
    else:
        print("don't found backup directory " + backup_dir + ", try to build one...")
        os.mkdir(backup_dir)
except IOError, err:
    print err
    sys.exit()

newday = date.today()    #获取今天的日期
oldday = date.today()-timedelta(5)    #获得5天前的日期
newfile = backup_dir + '/' + 'backup_data_' + str(newday.year) + '.' + str(newday.month) + '.' +  str(newday.day) + '.zip'    #本次备份的文件名(绝对路径)
oldfile = backup_dir + '/' + 'backup_data_' + str(oldday.year) + '.' + str(oldday.month) + '.' +  str(oldday.day) + '.zip'    #5天前备份的文件名(绝对路径)
newdb = backup_dir + '/' + 'backup_db_' + str(newday.year) + '.' + str(newday.month) + '.' +  str(newday.day) + '.sql.gz'    #本次导出的数据库名
olddb = backup_dir + '/' + 'backup_db_' + str(oldday.year) + '.' + str(oldday.month) + '.' +  str(oldday.day) + '.sql.gz'    #5天前导出的数据库名
  
print("today is " + str(newday.year) + "." + str(newday.month) + "." +  str(newday.day))

print("delete old backup data...")    #删除本机上5天前的备份文件
try:
    if os.path.isfile(oldfile):
        os.remove(oldfile)
        print("found old data at local, deleted it.")
    else:
        print("doesn't found old data at local, jumped.")
    if os.path.isfile(olddb):
        os.remove(olddb)
        print("found old db at local, deleted it.")   
    else:
        print("doesn't found old db at local, jumped.")
except IOError, err:
    print err
    sys.exit()

print("compress your website directory...")    #压缩网站目录
try:
    f = zipfile.ZipFile(newfile,'w',zipfile.ZIP_DEFLATED)
    for dirpath, dirnames, filenames in os.walk(website_dir):
        for filename in filenames:
            f.write(os.path.join(dirpath,filename))
    f.close()
    print("compressed webiste directory completely! file name is " + newfile)
except IOError, err:
    print err
    sys.exit()

print("export your databases...")    #导出数据库
try:
    cmd1 = "mysqldump -u" + mysql_user + " -p" + mysql_password + " --all-databases | gzip > " + newdb
    h = commands.getstatusoutput(cmd1)
    if h[0] == 0:
        print("export databases successful, continue processing...")
    else:
        print("export databases failed. please check your mysql username or password, or check mysql server status.")
        sys.exit()
except IOError, error:
    print error
    sys.exit()

print("prepare upload your backup data to remote ftp server...")

def upload():
    socket.setdefaulttimeout(60)    #超时FTP时间设置为60秒
    ftp = FTP(ftp_server)
    print("login ftp...")
    try:
        ftp.login(ftp_user, ftp_password)    #登陆FTP
        print(ftp.getwelcome().decode("GB2312").encode("UTF-8"))   #获得欢迎信息

        try:
            if ftp_backup_dir in ftp.nlst():
                print("found backup folder in ftp server, upload processing.")
            else:
                print("doesn't found backup folder in ftp server, try to build it.")
                ftp.mkd(ftp_backup_dir)
        except:
            print("the folder " + ftp_backup_dir + " doesn't exist and can't be create!")
            sys.exit()
    except:
        print("ftp login failed. exit.")
        sys.exit()
    ftp.cwd(ftp_backup_dir)    #设置FTP路径

    print("upload data...")
    try:
        ftp.storbinary('STOR ' + os.path.basename(newfile), open(newfile,'rb'), 1024)  #上传备份文件
        ftp.storbinary('STOR ' + os.path.basename(newdb), open(newdb,'rb'), 1024)  #上传导出的数据库
    except:
        print("upload failed. check your permission.")
        sys.exit()
   
    print("delete old file...")
    if os.path.basename(oldfile) in ftp.nlst():
        ftp.delete(os.path.basename(oldfile))    #删除5天前的备份文件
        print("found old data file at ftp server, deleted it.")
    else:
        print("doesn't found old file at ftp server, jumped.")
    if os.path.basename(olddb) in ftp.nlst():
        ftp.delete(os.path.basename(olddb))
        print("found old db file at ftp server, deleted it.")
    else:
        print("doesn't found old db at ftp server, jumped.")

    print("ftp upload successful. exit...")
    ftp.quit()

if __name__== '__main__':
    upload()

延伸阅读

评论