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环境路径配置以及命令行运行脚本

python环境路径配置以及命令行运行脚本

本文实例为大家分享了python环境路径设置方法,以及命令行运行python脚本,供大家参考,具体内容如下 找Python安装目录,设置环境路径以及在命令行运行python脚本 第一点:...

Python单例模式的两种实现方法

Python单例模式的两种实现方法 方法一  import threading class Singleton(object): __instance = N...

Python实现的简单算术游戏实例

本文实例讲述了Python实现的简单算术游戏。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python from operator import add,...

python中通过selenium简单操作及元素定位知识点总结

python中通过selenium简单操作及元素定位知识点总结

  浏览器的简单操作 # 导入webdriver模块 # 创建driver对象,指定Chrome浏览器 driver = webdriver.Chrome() # 窗口...

Python爬豆瓣电影实例

Python爬豆瓣电影实例

文件结构 html_downloader.py - 下载网页html内容 #!/usr/bin/python # -*- coding: UTF-8 -*- import urll...