Python 实现文件打包、上传与校验的方法

yipeiwu_com6年前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

以上这篇Python 实现文件打包、上传与校验的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python使用struct处理二进制的实例详解

Python使用struct处理二进制的实例详解 有的时候需要用python处理二进制数据,比如,存取文件,socket操作时.这时候,可以使用python的struct模块来完成.可以...

使用python进行文本预处理和提取特征的实例

如下所示: <strong><span style="font-size:14px;">文本过滤</span></strong>...

python数据类型_元组、字典常用操作方法(介绍)

元组 Python的元组与列表类似,不同之处在于元组的元素不能修改。 元组使用小括号,列表使用方括号。 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。 tp=(1,2,...

PyQt实现界面翻转切换效果

PyQt实现界面翻转切换效果

PyQt实现界面翻转切换效果是用qt的场景功能来实现的,用到了QGraphicsView,QGraphicsLinearLayout,QGraphicsWidget等有关qt场景的库。算...

Python函数中的函数(闭包)用法实例

本文实例讲述了Python闭包的用法。分享给大家供大家参考,具体如下: Python函数中也可以定义函数,也就是闭包。跟js中的闭包概念其实差不多,举个Python中闭包的例子。 d...