这里有新鲜出炉的Fabric 中文文档,程序狗速度看过来!
Fabric 是一个 Python (2.5 或更高) 库和命令行工具,用于连接到 SSH 服务器并执行命令。
下面介绍三个比较典型的应用Fabric的示例,涉及文件上传与校验,环境部署,代码发布功能
示例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()
来源: http://www.phperz.com/article/17/1026/351455.html