Fabric 是一个 Python (2.5-2.7) 的库和命令行工具,用来提升基于 SSH 的应用部署和系统管理效率。
更具体地说,Fabric 是:python
天然而然地,大部分用户把这两件事结合着用,使用Fabric来写和执行Python函数或task,以实现与远程服务器的自动化交互。让咱们一睹为快吧。git
建立.pip目录和配置文件:shell
cd ~ mkdir .pip cd .pip touch pip.conf
编辑文件pip.conf以下windows
[global] index-url=http://mirrors.zte.com.cn/pypi/simple [install] trusted-host=mirrors.zte.com.cn
安装依赖包(若是是centos的,须要使用yum安装)centos
sudo apt-get update sudo apt-get upgrade sudo apt-get install python-dev sudo apt-get install libffi-dev
用pip安装fabricapi
sudo pip install fabric
编写fabfile.py以下:bash
def hello(): print("hello world!") def helloEx(name): print("hello ", name, "!")
在fabfile文件所在目录执行以下命令:服务器
wld@trusty:~/fabric$ fab hello hello world! Done.
编写fabfile.py以下:app
def hello(name): print("hello "+name+" !")
在fabfile文件所在目录执行以下命令:ssh
wld@trusty:~/fabric$ fab hello:name=wld hello wld! Done.
fabric.api包里的local()方法能够用来执行本地Shell命令:
from fabric.api import local def hello(): local('ls -l ~')
local()方法有一个”capture”参数用来捕获标准输出,好比:
def hello(): output = local('ls -l ~', capture=True)
这样,Hello字样不会输出到屏幕上,而是保存在变量output里。
Fabric真正强大之处不是在执行本地命令,而是能够方便的执行远程机器上的Shell命令。它经过SSH实现,你须要的是在脚本中配置远程机器地址及登陆信息:
from fabric.api import * env.passwords = { "user@10.1.1.1:22":"password" } @hosts("user@10.1.1.1:22") def hello(): run("ls -l ~")
咱们能够经过设置env.passwords来避免在运行过程当中输密码,注意ip后面须要加端口号,示例中的22是ssh的端口号。
有时候咱们须要经过一台中起色器才能登陆内网机器,这种状况须要设置env.gateway
from fabric.api import * env.gateway = "user@10.1.1.2:22" env.passwords = { "user@10.1.1.1:22":"password1" "user@123.1.1.1:22":"password2" } @hosts("user@123.1.1.1:22") def hello(): run("ls -l ~")
首先windows机器须要安装ssh服务,注意ssh服务所用的帐户须要设置可以运行exec的权限,不然没法启动windwos程序。
其次因为fabric默认使用bash,所以须要设置变量env.shell="cmd /c",不然会报错。
若是对于不一样的服务器,咱们想执行不一样的任务,咱们要对服务器定义角色:
from fabric.api import env, roles, run, execute, cd env.roledefs = { 'staging': ['bjhee@example1.com','bjhee@example2.com'], 'build': ['build@example3.com'] } env.passwords = { 'staging': '11111', 'build': '123456' } @roles('build') def build(): with cd('/home/build/myapp/'): run('git pull') run('python setup.py') @roles('staging') def deploy(): run('tar xfz /tmp/myapp.tar.gz') run('cp /tmp/myapp /home/bjhee/www/') def task(): execute(build) execute(deploy)
如今让咱们执行fab task,这时Fabric会先在一台build服务器上执行build任务,而后在两台staging服务器上分别执行deploy任务。”@roles”装饰器指定了它所装饰的任务会被哪一个角色的服务器执行。