
研究了一下,真是不錯的東西,
就裝來用了。
安裝其實很簡單,但我搞了一會…
因為我少裝了 setuptools ,一直沒發現…還一直在找那裡出錯了 @ @
簡單記錄一下安裝的步驟吧,詳細見( Fabric Installtion ):
1. 要有 python,python-setuptools
2. 我是用 pip 來安裝,所以要有pip
# curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
# python get-pip.py
3. 接著執行 pip install fabric ,就搞定了。 # python get-pip.py
4. 在執行 fab 的目錄下建 fabfile.py ,我是直接放在 ~
附上一個我亂寫的 fabfile.py Sample
import fabric from fabric.api import run, env, local from fabric.operations import put env.warn_only = True # Broken machine env.skip_bad_hosts = True env.parallel = True env.pool_size = 5 env.timeout = 1 fabric.state.output["status"] = False fabric.state.output["running"] = False fabric.state.output["user"] = False fabric.state.output["warnings"] = False fabric.state.output["stderr"] = False # Initial Server List web = [] img = [] all = [] # Web Server for x in xrange(1,10): web.append('web-' + str(x)) all.append('web-' + str(x)) # Img Server for x in xrange(11,20): img.append('img-' + str(x)) all.append('img-' + str(x)) env.roledefs = { 'web' : web, 'img' : img, 'all' : all } def who(): ''' Who Am I ''' run('whoami') def enc(act='status'): ''' enc:start/stop/status ''' if act == 'status': print "Status" elif act == 'start': print "Start" elif act == 'stop': print "Stop" else: print "Else" def cmd(cmd='whoami'): ''' cmd:'/etc/init.d/lighttpd status' ''' run(cmd) def lighty(act='status'): ''' lighty:start/stop/restart ''' run('/etc/init.d/lighttpd ' + act)
存好檔後,執行
# fab --list
會出現如下圖

範例中,我將所有的Server 分為 web, img 和 all 三群
並設定了四個指令
cmd : 可以輸入任何指令
enc : 主要是表示可以用 if else 來判斷輸入的值,做對應的事
lighty : 如果是這種固定的服務,可以直接下 start / stop 來啟動 / 關閉
who : 就是寫死的指令 whoami
執行的方式如下
# fab -R web cmd:date
# fab -R img cmd:'ps -ef | grep php'
# fab -R all enc:stop
# fab -R img lighty:start
# fab -R all who
# fab -R img cmd:'ps -ef | grep php'
# fab -R all enc:stop
# fab -R img lighty:start
# fab -R all who
另外還有 put 可以拿來Sync File ,真是個很好用的東西耶。
Fabric 上還有更多更進階的用法。
補充:
程式基本上同上,只是再加上一些東東,所以就只貼有新增的東西啦
import fabric # 多加了 roles, parallel, serial from fabric.api import run, env, roles, parallel, serial # .... 略 # 針對 web 群組,這樣就不用再指令加上 -R web 了 @roles('web') def squid(act='status'): ''' squid:start/stop/restart - @roles(web) ''' run('/etc/init.d/squid ' + act) # 依序執行 @serial def nginx(act='status'): ''' nginx:start/stop/restart ''' run('/etc/init.d/nginx ' + act) # 針對 img 群組,同步執行,並設定 pool_size = 10 @roles('img') @parallel(pool_size=10) def lighty(act='status'): ''' lighty:start/stop/restart - @roles(img) ''' run('/etc/init.d/lighttpd ' + act) # 簡單的 Sync File,針對相同路徑。 def sync(file): print("Executing on %(host)s as %(user)s" % env) print "\t put " + file + " -> " + file put(file, file)
另外可以在 ~ 下建一個檔案 .fabricrc
內容是
fabfile="~/fabfile.py"
這樣子在任何地方都可以執行 fabric 了。
當然裡面也可以加入其它的設定,
可見:The environment dictionary
0 comments:
張貼留言