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

yipeiwu_com5年前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判断是否json是否包含一个key的方法

如下所示: jsonObject 是个json if (key in jsonObject) : print '有' else: print '没有' 以上这篇Python判断...

跟老齐学Python之开始真正编程

跟老齐学Python之开始真正编程

通过对四则运算的学习,已经初步接触了Python中内容,如果看官是零基础的学习者,可能有点迷惑了。难道在IDE里面敲几个命令,然后看到结果,就算编程了?这也不是那些能够自动运行的程序呀?...

Python闭包函数定义与用法分析

本文实例分析了Python闭包函数定义与用法。分享给大家供大家参考,具体如下: python的闭包 首先python闭包的作用,一个是自带作用域,另一个是延迟计算。 闭包是装饰器的基础。...

详解Python实现进度条的4种方式

详解Python实现进度条的4种方式

这里只列举了部分方法,其他方法或python库暂时还没使用到 1.不用库,直接打印: 代码样例: import time #demo1 def process_bar(percent...

Python判断Abundant Number的方法

本文实例讲述了Python判断Abundant Number的方法。分享给大家供大家参考。具体如下: Abundant Number,中文译成:盈数(又称 丰数, 过剩数abundant...