Back to Build_Automation, See Alse Python


Fabric 是基于 SSH 协议的 Python 工具,相比传统的 ssh/scp 方式,用 Python 的语法写管理命令更易读也更容易扩展,管理单台或者多台机器犹如本地操作一般。


1. fab如何工作?


2. Quick Start

2.1. Installation

virtualenv /srv/fabric/pythonenv
source /srv/fabric/pythonenv/bin/activate
pip install fabric
ln -s /srv/fabric/pythonenv/bin/fab ~/app/bin/fab

Issue: pip install pycrypto, with error info below

src/MD2.c:31:20: fatal error: Python.h: No such file or directory

compilation terminated.

error: command 'gcc' failed with exit status 1

fix by install python-dev

sudo apt-get install python-dev

Issue: The read operation timed out(default is 15 seconds)

pip install fabric --timeout 1000

2.2. Writing

def hello(name="world"):
    print("Hello %s!" % name)

$ fab hello:twotwo
Hello twotwo!

2.3. Fabric的执行

Execution model

2.3.1. Defining host lists

from fabric.api import env

env.roledefs = {
    'web': {
        'hosts': ['www1', 'www2', 'www3'],
        'foo': 'bar'
    'dns': {
        'hosts': ['ns1', 'ns2'],
        'foo': 'baz'

2.3.2. Per-task

from fabric.api import hosts, run

@hosts('host1', 'host2')
def mytask():
    run('ls /var/www')

my_hosts = ('host1', 'host2')
def mytask():
    # ...

2.3.3. Combining host lists

from fabric.api import env, hosts, roles, run

env.roledefs = {'role1': ['b', 'c']}

@hosts('a', 'b')
def mytask():
    run('ls /var/www')

2.4. 常用配置           -- 主机ip,当然也可以-H参数指定
env.password       -- 密码,打好通道的请无视
env.roledefs       -- 角色分组,比如:{'web': ['x', 'y'], 'db': ['z']}

from fabric import env
env.hosts = ['user1@host1:port1', 'user2@host2.port2']
env.passwords = {'user1@host1:port1': 'password1', 'user2@host2.port2': 'password2'}

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

2.5. Fabric API

fabric.operations: 最常用的函数

3. fab usages

3.1. a deployment sample

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from fabric.api import local, cd, sudo
from fabric.api import put, get
from fabric.api import env, task, run

def deploy():
    put('/srv/fabric/apache-jmeter-2.9.tar.gz','.') #put jmeter to remote:~
    run('tar xzf apache-jmeter-2.9.tar.gz')

refer to
def start():
    run('screen -wipe', warn_only=True)
    #run('screen -S jmeter -d -m apache-jmeter-2.9/bin/jmeter-server')
    run('screen -S jmeter -d -m apache-jmeter-2.9/bin/jmeter-server; sleep 1')
    run('screen -ls |grep jmeter', warn_only=True)

4. Cask


brew tap phinze/homebrew-cask && brew install brew-cask

5. Reference

5.1. All My Fab Scripts


MainWiki: Fabric (last edited 2013-07-09 23:45:22 by twotwo)