Fabric是一個(gè)Python庫,用于簡(jiǎn)化使用SSH的應(yīng)用程序部署或系統(tǒng)管理任務(wù)。
它提供的操作包括:執(zhí)行本地或遠(yuǎn)程shell命令,上傳/下載文件,以及其他輔助功能等。
安裝
安裝fabric庫
pip install fabric
依賴 Paramiko 、PyCrypto庫
安裝依賴
# 安裝 pycrypto 密碼庫
pip install pycrypto
# 安裝 pycrypto 依賴
pip install ecdsa
ps:【windows7 x64 ,python2.7 】Windows下pip安裝包報(bào)錯(cuò):Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat ,可以安裝Micorsoft Visual C++ Compiler for Python 2.7 。
fabric使用
新建py腳本:fabfile.py
def hello():
print("Hello world!")
def hi():
print("Hello world!")
執(zhí)行fab命令:執(zhí)行hello函數(shù)
fab hello
如果當(dāng)前模塊下沒有fabfile.py文件,那么需要指定-f參數(shù).
fab -f test.py hello
使用參數(shù)
def hello(name, value):
print("%s = %s!" % (name, value))
帶參執(zhí)行命令
fab hello:name=age,value=20
執(zhí)行本地操作
from fabric.api import local, lcd
def lsfab():
with lcd('~/tmp/fab'):
local('ls')
執(zhí)行遠(yuǎn)程操作
def setting_ci():
local('echo "add and commit settings in local"')
def update_setting_remote():
print "remote update"
with cd('~/temp'): #cd用于進(jìn)入某個(gè)目錄
run('ls -l | wc -l') #遠(yuǎn)程操作用run
多服務(wù)器操作
#!/usr/bin/env python
# encoding: utf-8
from fabric.api import *
env.roledefs = {
'testserver': ['user1@host1:port1',],
'productserver': ['user2@host2:port2', ]
}
@roles('testserver')
def task1():
run('ls -l | wc -l')
@roles('productserver')
def task2():
run('ls ~/temp/ | wc -l')
def do():
execute(task1)
execute(task2)
用不同顏色打印
from fabric.colors import *
def show():
print green('success')
print red('fail')
print yellow('yellow')
fabric 命令行工具
裝飾器作用?
@task # 定義任務(wù) @task(alias='dwm') fab --list
@parallel # 并行處理
命令行常用: fab --help
fab -l -- 顯示可用的task(命令)
fab -H -- 指定host,支持多host逗號(hào)分開
fab -R -- 指定role,支持多個(gè)
fab -P -- 并發(fā)數(shù),默認(rèn)是串行
fab -w -- warn_only,默認(rèn)是碰到異常直接abort退出
fab -f -- 指定入口文件,fab默認(rèn)入口文件是:fabfile/fabfile.py