fabric 是一個python包 是一個基於ssh的部署工具包
通常用來對網站 微服務等等的批量部署 例如 我有5台線上服務器 可以通過一台對着5台分發,實現自動部署的目的。
簡單介紹下 fabric的常用命令
常用命令
lcd(dir): 進入本機某目錄
local(cmd): 本機上執行命令
cd(dir): 進入服務器某目錄
run(cmd):服務器上執行命令
例如一下腳本:
from datetime import datetime from fabric.api import * # 登錄用戶和主機名: env.user = 'root'
env.password='xxxxx' env.hosts = ['192.168.0.1','192.168.0.2'] # 如果有多個主機,fabric會自動依次部署 def pack(): ' 定義一個pack任務 ' # 打一個tar包: tar_files = ['*.py', 'static/*', 'templates/*', 'favicon.ico'] local('rm -f example.tar.gz') local('tar -czvf example.tar.gz --exclude=\'*.tar.gz\' --exclude=\'fabfile.py\' %s' % ' '.join(tar_files)) def deploy(): ' 定義一個部署任務 ' # 遠程服務器的臨時文件: remote_tmp_tar = '/tmp/example.tar.gz' tag = datetime.now().strftime('%y.%m.%d_%H.%M.%S') run('rm -f %s' % remote_tmp_tar) # 上傳tar文件至遠程服務器: put('shici.tar.gz', remote_tmp_tar) # 解壓: remote_dist_dir = '/srv/www.example.com@%s' % tag remote_dist_link = '/srv/www.example.com' run('mkdir %s' % remote_dist_dir) with cd(remote_dist_dir): run('tar -xzvf %s' % remote_tmp_tar) # 設定新目錄的www-data權限: run('chown -R www-data:www-data %s' % remote_dist_dir) # 刪除舊的軟鏈接: run('rm -f %s' % remote_dist_link) # 創建新的軟鏈接指向新部署的目錄: run('ln -s %s %s' % (remote_dist_dir, remote_dist_link)) run('chown -R www-data:www-data %s' % remote_dist_link) # 重啟服務: fcgi = '/etc/init.d/py-fastcgi' with settings(warn_only=True): run('%s stop' % fcgi) run('%s start' % fcgi)
運行命令 :
$ fab pack
$ fab deploy
相關鏈接 :
http://www.liaoxuefeng.com/article/001373892650475818672edc83c4c978a45195eab8dc753000
http://docs.fabfile.org/en/1.10/tutorial.html