首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python Fabric 自動化部署實戰:本地/遠端命令、多伺服器角色、密碼管理

     編輯:更多程式設計知識

Fabric 是 Python 寫成的 SSH 自動化部署工具,將重複的部署流程固化為腳本,支援多機器並行操作。

安裝與 Hello World


pip install fabric
# fabfile.py
def hello():
    print("Hello world!")
# 執行:fab hello

參數傳遞


def hello(name, value):
    print("%s = %s!" % (name, value))
# fab hello:name=age,value=20

本地命令


from fabric.api import local
def lsfab():
    local('cd ~/tmp/fab && ls')

遠端命令與混合部署


from fabric.api import env, cd, run
env.hosts = ['user@host:port']
env.password = 'pwd'

def update_setting_remote():
    with cd('~/temp'):
        run('ls -l | wc -l')

多伺服器角色


env.roledefs = {
    'testserver': ['user1@host1:port1'],
    'realserver': ['user2@host2:port2']
}

@roles('testserver')
def task1(): run('ls -l | wc -l')

@roles('realserver')
def task2(): run('ls ~/temp/ | wc -l')

def dotask():
    execute(task1)
    execute(task2)

輸出顏色


from fabric.colors import green, red, yellow
print(green('success')); print(red('fail'))

密碼管理


env.hosts = ['host1', 'host2']
env.passwords = {
    'host1': 'pwd1',
    'host2': 'pwd2'
}
# 或配合 roledefs
env.roledefs = {...}
env.passwords = {'host1': '...', 'host2': '...', 'host3': '...'}

優勢總結

  • Python 語法,易維護擴展
  • 本地/遠端統一 API
  • 角色分組管理多環境
  • 比 Shell 腳本更結構化
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved