1. 程式人生 > >Python之——實現檔案打包、上傳與校驗

Python之——實現檔案打包、上傳與校驗

不多說,我們直接上原始碼:

# -*- coding:UTF-8 -*-
'''
實現檔案打包、上傳與校驗
Created on 2018年1月12日

@author: liuyazhuang
'''

from fabric.api import *
from fabric.context_managers import *
from fabric.contrib.console import confirm

env.user = 'root'
env.hosts = ['10.2.2.2']
env.password = 'cardio-2017'

@task
@runs_once
def tar_task():    #本地打包任務函式,只限執行一次
    with lcd("/data/logs"):
        local("tar -czf access.tar.gz access.log")
        

@task
def put_task():     #上傳檔案任務函式
    run("mkdir -p /nginx/logs")
    with cd("/nginx/logs"):
        #put(上傳操作)出現異常時,繼續執行,非終止
        with settings(warn_only = True):
            result = put("/data/logs/access.tar.gz", "/nginx/logs/access.tar.gz")
        if result.failed and not confirm("put file failed, Contiunue[Y/N]?"):
            #出現異常時,確認使用者是否繼續,(Y繼續)
            abort("Aborting file put task!")

@task
def check_task():   #校驗檔案任務函式
    with settings(warn_only = True):
        #本地local命令需要配置capture=True才能捕獲返回值
        lmd5 = local("md5sum /data/logs/access.tar.gz", capture=True).split(' ')[0]
        rmd5 = run("md5sum /nginx/logs/access.tar.gz").split(' ')[0]
        #對比本地與遠端檔案的md5資訊
        if lmd5 == rmd5:
            print "OK";
        else:
            print "ERROR"

@task
def execute():      #統一執行tar_task()、put_task()、check_task()
    tar_task()
    put_task()
    check_task()
本例項分別定義了3個功能函式,實現了檔案的打包、上傳和校驗的功能,且3個功能相互獨立,可分開執行
fab -f file_handler.py tar_task			#檔案打包操作
fab -f file_handler.py put_task			#檔案上傳操作
fab -f file_handler.py check_task		#檔案校驗操作
也可以通過以下命令組合在一起執行
fab -f file_handler.py execute