最近公司給了臺web測試服務器,最近正好學習python語言的flask框架,琢磨著搭個小博客玩玩,但是每次修改代碼后,都需要重新打包代碼,然后sftp到服務器,再解壓,重啟服務。作為一個懶人當然不能忍,于是乎發現了這貨-fabric。
fabric是python語言實現的一個利用ssh高效部署和管理系統的工具。
安裝
省略python、pip管理工具安裝過程
<pre>pip install fabric</pre>
驗證是否安裝成功
進入python編輯模式,輸入代碼,無錯即表示成功安裝
<pre>from fabric.api import local</pre>
fabric版hello world
fabric 默認文件fabfile.py,當然如果不想用這個名字,需要加<code>-f</code>參數
創建fabfile.py文件
<pre>vim fabrile.py</pre>編輯代碼
<pre>#coding:utf-8
from fabric.api import local#
def hello():
# local函數用來執行本地命令
local('echo "hello wolrd!"')
</pre>執行代碼
<pre>fab hello</pre>
可以通過<code>fab -l</code>查看可以執行的任務,當前為<code>hello</code>函數運行結果
[localhost] local: echo "hello world!"
hello world!
Done.
fabric常用api
函數 | 解釋 | 例子 |
---|---|---|
local | 執行本地命令 | local('ls -l') |
lcd | 切換本地目錄(需要with包裹) | lcd('本地目錄') |
run | 執行遠程命令 | run('ls -l') |
cd | 切換遠程目錄(需要with包裹) | cd('遠程目錄') |
put | 將本地文件上傳至遠程目錄 | put('本地文件','遠程目錄') |
env | fabric環境,配置遠程ip、端口、密碼 | 見下文 |
fabric遠程執行例子
將本地/tmp/local目錄下創建hello.txt(內容“hello world!”)文件上傳至服務器/tmp/remote上,并顯示txt文件內容
<pre>
coding:utf-8
from fabric.api import local,cd,put,lcd,env,run
# 目標hosts(可多個),用戶@ip:22,使用ssh
env.hosts = ['root@remoteip:22']
# root密碼
env.password='pwd'
def hello():
# 切換到本地/tmp/local目錄
with lcd('/tmp/local'):
# 執行本地命令
local('echo "hello world!" > hello.txt')
# 上傳至服務器
put('hello.txt','/tmp/remote')
# 切換到服務器/tmp/remote目錄
with cd('/tmp/remote'):
# 執行服務器命令
run('cat hello.txt')
</pre>
運行結果
fab hello
[root@remoteip:22] Executing task 'hello'
[localhost] local: echo "hello world!" > hello.txt
[root@remoteip:22] put: /tmp/local/hello.txt -> /tmp/remote/hello.txt
[root@remoteip:22] run: cat hello.txt
[root@remoteip:22] out: hello world!
多個目標服務器
相同密碼或者手動輸入:
<pre>env.hosts = ['root@ip1:22',root@ip2:22]</pre>不同密碼或者不想手動輸入(此方法也可定義不角色一組服務器):
<pre>#coding:utf-8
from fabric.api import local,cd,put,lcd,env,run,execute,roles
env.roledefs = {
'role1':['root@ip1:22',],
'role2':['root@ip2:22',]
}
env.passwords={
'root@ip1:22':'pwd1',
'root@ip2:22':'pwd2'
}
@roles('role1')
def role1():
with cd('/tmp'):
run('ls -l')
@roles('role2')
def role2():
with cd('/tmp'):
run('ls')
def task():
execute(role1)
execute(role2)
</pre>
最后記錄我部署代碼,方便日后參考
<pre>
-- coding:utf-8 --
from fabric.api import local, cd, put, lcd, settings, env, run
import os
import time
env.hosts = ['root@remoteiip:22']
env.password = 'pwd'
tar_file = 'minibbs.tar.gz'
loc_tar_path = 'dist'
def _pack():
# 當前目錄在minibss/dist下
include = ['../minibbs/static/', '../minibbs/templates/', '../minibbs/.py', '../minibbs/.db', '../run.py']
# 發生錯誤僅僅給出警告,而不是退出
with settings(warn_only=True):
local('rm -f %s' % os.path.join(loc_tar_path, tar_file))
with lcd(loc_tar_path):
local('tar -czvf {tar_file} --exclude=\\'{tar_file}\\' {include}'.
format(tar_file=tar_file, include=' '.join(include)))
def _deploy():
remote_tar_path = '/root/haort/venv/tmp/' + tar_file
with settings(warn_only=True):
run('rm -f %s' % remote_tar_path)
put(os.path.join(loc_tar_path, tar_file), remote_tar_path)
remote_pro = 'minibbs' + time.strftime('%Y%m%d%H%M', time.localtime())
remote_proj_dir = '/root/haort/venv/' + remote_pro
with settings(warn_only=True):
run('mkdir %s' % remote_proj_dir)
with cd(remote_proj_dir):
run('rm -rf %s' % '*')
run('tar -xzvf %s' % remote_tar_path)
with cd('/root/haort/venv/'):
run('rm -f minibbs')
run('ln -s %s minibbs' % remote_pro)
run('supervisorctl stop minibbs')
run('supervisorctl start minibbs')
def task():
_pack()
_deploy()
</pre>