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数据可视化正态分布简单分析及实现代码

Python数据可视化正态分布简单分析及实现代码

Python说来简单也简单,但是也不简单,尤其是再跟高数结合起来的时候。。。 正态分布(Normaldistribution),也称“常态分布”,又名高斯分布(Gaussiandistr...

对python requests的content和text方法的区别详解

问题: 一直在想requests的content和text属性的区别,从print 结果来看是没有任何区别的 看下源码: @property def text(self):...

基于python的selenium两种文件上传操作实现详解

基于python的selenium两种文件上传操作实现详解

方法一、input标签上传 如果是input标签,可以直接输入路径,那么可以直接调用send_keys输入路径,这里不做过多赘述,前文有相关操作方法。 方法二、非input标签上传 这种...

python切片及sys.argv[]用法详解

一、python切片 a=a[::-1] 倒序 a=a[1:10:2] 下标1~10,以2间隔取 a=a[::2] 2间隔返回a[:] a=[1,2,3,4,5,6,7] print...

pytorch中tensor张量数据类型的转化方式

1.tensor张量与numpy相互转换 tensor ----->numpy import torch a=torch.ones([2,5]) tensor([[1.,...