python备份远程FTP脚本

自己写的一个Linux上使用python备份远程FTP脚本,编写此脚本的初衷是为了方便一些使用虚拟主机的朋友,因为许多虚拟主机商不提供备份服务,导致文件丢失的情况时有发生,因此就有了这个脚本。

系统需要安装fuse-curlftpfs、zlib、zlib-devel三个软件包,其中fuse-curlftpfs包不好安装,得先安装个第三方的yum源,才可以通过yum的方式安装之。

原理比较简单,即是python调用shell命令把远程FTP服务器挂载至本地,再打包压缩实现备份,最后解除挂载。备份以后的文件名会包含了备份的日期,同时会删除5天前备份的文件,配合crontab使用,可以实现定期备份FTP服务器上的文件。

如果是在VPS上使用,请确保VPS是不是基于Openvz虚拟化技术的,因为Openvz会限制对fuse的使用,无法实现远程挂载。Xen,KVM可以正常使用。

编写脚本期间还得到了zhiwei同学的帮助,在此提出感谢。脚本具备扩展性,可以备份多个FTP服务器上的目录。如果需要备份多个FTP,把脚本最后4行复制一遍即可。

使用方法:

1,安装第三方yum源

Centos5 64位  wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el5.rf.x86_64.rpm
Centos5 32位  wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el5.rf.i386.rpm
Centos6 64位  wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm
Centos6 32位  wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm

安装下载回来的rpm软件包
rpm -ivh rpmforge-release-0.5.3-1.el5.rf.x86_64.rpm

安装基础软件包
yum install python fuse-curlftpfs zlib -y

2,新一个.py格式的文件,文件内容如下

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

class Package:
    """
    检查fuse-curlftpfs软件包的安装与否,如果没有,则安装之
    """

    def __init__(self,name):
        self.name=name
    def install(self):
        print('execute "yum install ' + self.name + '"...')
	#cmd=commands.getstatusoutput('yum install ' +  self.name + ' -y')
        print os.system('yum install ' +  self.name + ' -y')
        if self.name in os.popen('rpm -qa | grep ' + self.name).read():
	    print('Install ' + self.name + ' successful.')
        else:
            print('Install ' + self.name + ' failed, aborting.')
            sys.exit()
    def checkinstall(self):
	cmd=commands.getstatusoutput('rpm -qa | grep ' +  self.name)
        if self.name in cmd[1]:
            print(self.name + ' has aleady installed. Continue...')
        else:
            print(self.name + ' isn\'t installed. Ready to install it.')
	    self.install()

class Backup:
    """
    使用shell命令挂载之,然后执行备份过程(压缩目录,删除旧文件),压缩完成以后再解除挂载
    """

    def __init__(self,server,user,passwd,backupname):
        self.server=server
        self.user=user
        self.passwd=passwd
        self.backupname=backupname
    def mount(self):
        try:
            if os.path.isdir('/' + self.backupname):
                print('found mount point /' + self.backupname + ', ready to mount ftp server.')
            else:
                print('doesn\'t found mount point /' + self.backupname + ', build it.')
                os.mkdir('/' + self.backupname)
        except IOError, error:
            print error
            sys.exit()

        cmd=commands.getstatusoutput(r'curlftpfs ftp://' + self.user + ':' + self.passwd + '@' + self.server + r' /' + self.backupname + ' -o codepage=utf8')
        print cmd[1]

        pat=r'fuse(.+)/' + self.backupname
        all=os.popen('df -hT').read()
        if re.search(pat,all):
            print('mounted /' + self.backupname + ', continue...')
        else:
            print('mount failed. please check.')
            sys.exit()

    def backup(self):
        newday = date.today()    #获取今天的日期
        oldday = date.today()-timedelta(5)    #获得5天前的日期
        newfile = self.backupname + '_backup_' + str(newday.year) + '.' + str(newday.month) + '.' +  str(newday.day) + '.zip'    #本次备份的文件名
        oldfile = self.backupname + '_backup_' + str(oldday.year) + '.' + str(oldday.month) + '.' +  str(oldday.day) + '.zip'    #5天前备份的文件名

        print('delete old file...')
        try:
            if os.path.isfile(oldfile):
                os.remove(oldfile)
            else:
                print('don\'t found old file, jumped.')
        except IOError, err:
            print err

        print('compress directory. it will take a while.')
        try:
            f = zipfile.ZipFile(newfile,'w',zipfile.ZIP_DEFLATED)
            for dirpath, dirnames, filenames in os.walk(r'/' + self.backupname):
                for filename in filenames:
                    f.write(os.path.join(dirpath,filename))
            f.close()
            print("backup completely! file name is " + newfile)
        except (IOError, OSError), err:
            print err
            self.umount()
            sys.exit()

    def umount(self):
        cmd=commands.getstatusoutput('umount /' + self.backupname)

        pat=r'fuse(.+)/' + self.backupname
        all=os.popen('df -hT').read()
        if not re.search(pat,all):
            print('umounted /' + self.backupname + '. Done!')
        else:
            print('umount failed. please check.')


if __name__=='__main__':
    ps=Package('fuse-curlftpfs')
    ps.checkinstall()

    #标示符是挂载到本的的文件名,及压缩以后的文件名,只能用英文且不能有空格,可以用下划线
    #如果要备份多个FTP,把下面4行复制一遍即可,注意每个的标示符不能一样
    bu=Backup('FTP地址','用户名','密码','标示符')
    bu.mount()
    bu.backup()
    bu.umount()

发表评论

电子邮件地址不会被公开。