Fabric简明教程

jopen 10年前


Fabric是一个Python(2.5-2.7)的支持库和命令行工具,用于流水线式执行SSH,以实现应用部署或系统管理。详情查看官方网站以及官方文档

Hello

安装

pip install fabric

编写脚本

vim fabfile.py    def hello():      print("Hello world!")

运行脚本

fab hello

常见命令

fab --help  fab -l      # 显示可用的task(命令)  fab -H      # 指定host,支持多个host,以逗号分开  fab -R      # 指定role,支持多个role  fab -P      # 并发数,默认串行  fab -w      # warn_only,默认遇到异常直接abort退出  fab -f      # 指定入口文件,默认fabfile.py

常用函数

lcd('/tmp')         # 切换本地目录  cd('/tmp')          # 切换远程目录    local('pwd')        # 执行本地命令  run('uname -a')     # 执行远程命令    sudo('/etc/init.d/nginx start')     # 执行远程sudo

错误处理

def test():      with settings(warn_only=True):          result = local('./manage.py test my_app', capture=True)      if result.failed and not confirm("Tests failed. Continue anyway?"):          abort("Aborting at user request.")

角色定义

host1 = 'user@192.168.1.1:22'  host2 = 'user@192.168.1.2:22'  host3 = 'user@192.168.1.3:22'    env.hosts = [ host1, host2, host3 ]    env.passwords = {      host1: "pwd_of_host1",      host2: "pwd_of_host2",      host3: "pwd_of_host3",  }

或者

env.roledefs = {      'nginx_user': [host1, host2],      'mysql_user': [host3]  }    env.passwords = {      host1: "pwd_of_host1",      host2: "pwd_of_host2",      host3: "pwd_of_host3",  }

简单实例

from __future__ import with_statement  from fabric.api import *  from fabric.contrib.console import confirm    host1 = 'user@192.168.1.1:22'  host2 = 'user@192.168.1.2:22'  host3 = 'user@192.168.1.3:22'    env.passwords = {      host1: "pwd_of_host1",      host2: "pwd_of_host2",      host3: "pwd_of_host3",  }    env.roledefs = {      'nginx_user': [host1, host2],      'mysql_user': [host3]  }    def test():      with settings(warn_only=True):          result = local('./manage.py test my_app', capture=True)          print("some processings")      if result.failed and not confirm("Tests failed. Continue anyway?"):          abort("Aborting at user request.")          print red("some error")    def deploy():      test()      local("git add -p && git commit")      local("git push")    @task  @parallel  @roles('nginx')  def nginx_start():      sudo('/etc/init.d/nginx start')    @task  @serial  @roles('nginx')  def nginx_stop():      sudo('/etc/init.d/nginx stop')    @task  @parallel(pool_size=5)  @roles('mysql')  def mysql_start()      sudo('/etc/init.d/mysql start')
来自:http://blog.willwong.cc/posts/fabricjian-ming-jiao-cheng.html#jtss-tsina