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 ljust rjust center输出

看下面的例子就会明白了: 复制代码 代码如下:print '|','*'.ljust(10),'|' print '|','*'.ljust(10,'-'),'|' print '|',...

Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析

Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析

本文实例讲述了Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)。分享给大家供大家参考,具体如下: demo.py(类方法,@classm...

python使用htmllib分析网页内容的方法

本文实例讲述了python使用htmllib分析网页内容的方法。分享给大家供大家参考。具体实现方法如下: import htmllib, urllib, formatter, sys...

简单了解python元组tuple相关原理

这篇文章主要介绍了简单了解python元组tuple相关原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 元组tuple和列表Lis...

用python找出那些被“标记”的照片

用python找出那些被“标记”的照片

源码传送门 环境准备 下面的两个第三方模块都可以直接通过pip快速安装,这里使用py36作为运行环境。 python3.6 requests exifread 思路...