fabric 安裝及使用

Fabric是一個(gè)Python庫,用于簡(jiǎn)化使用SSH的應(yīng)用程序部署或系統(tǒng)管理任務(wù)。

它提供的操作包括:執(zhí)行本地或遠(yuǎn)程shell命令,上傳/下載文件,以及其他輔助功能等。

安裝

?點(diǎn)我傳送到fabric官網(wǎng)

安裝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

?更多參考官網(wǎng)教程

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容