Fabric 应用案例

yipeiwu_com7年前Python基础

示例1:文件打包,上传与校验
我们时常做一些文件包分发的工作,实施步骤一般是先压缩打包,在批量上传至目标服务器,最后做一致性校验,本案例通过put()方法实现文件的上传,通过对比本地与远程主机文件的md5,最终实现文件一致性校验。

#!/usr/bin/env python
from fabric.api import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
env.user = 'root'
env.hosts = ['192.168.1.23','192.168.1.24']
env.password = '123456'
 
@runs_once
def tar_task(): #本地打包任务函数,只限执行一次
  with lcd('/'):
    local("tar zcvf auto.tar.gz auto")
 
def put_task():
  run('mkdir /data') #上传任务函数
  with cd("/data"):
    with settings(warn_only=True):
      result = put("/auto.tar.gz","/data") #put上传出现异常时继续执行,非中止
    if result.failed and not confirm("put file failed, Continue[Y/N]?"):
      abort('Aboring file put task!') #出现异常时,确认用户是否继续
 
def check_task():
  with settings(warn_only=True):
    lmd5 = local("md5sum /auto.tar.gz",capture=True).split(' ')[0]
    rmd5 = run("md5sum /data/auto.tar.gz").split(' ')[0]
    if lmd5 == rmd5: #对比本地及远程文件MD5信息
      print "ok"
    else:
      print ERROR
def go():
  tar_task()
  put_task()
  check_task()      

相关文章

正确理解python中的关键字“with”与上下文管理器

前言 如果你有阅读源码的习惯,可能会看到一些优秀的代码经常出现带有 “with” 关键字的语句,它通常用在什么场景呢?今天就来说说 with 和 上下文管理器。 对于系统资源如文件、数据...

Python使用selenium + headless chrome获取网页内容的方法示例

使用python写爬虫时,优选selenium,由于PhantomJS因内部原因已经停止更新,最新版的selenium已经使用headless chrome替换掉了PhantomJS,所...

Python访问MongoDB,并且转换成Dataframe的方法

如下所示: #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/13 11:10 # @Author : b...

Python实现文件按照日期命名的方法

本文实例讲述了Python实现文件按照日期命名的方法。分享给大家供大家参考。具体实现方法如下: 这里实现文件按照创建的时期批量重命名的功能 # -*- coding: utf-8 -...

使用PyInstaller将python转成可执行文件exe笔记

1、安装PyInstaller PyInstaller的作用如标题所说,首先需要下载PyInstaller和UPX,UPX是用来压缩exe的,点击超链接下载吧,目前稳定版本是1.3,注意...