unix繫上腳本能夠作到自動化運維;執行make,會自動尋找當前目錄下的makefile/Makefile文件; html
makefile語法: python
目標 : 條件 git
腳本 api
舉例: 運維
clean: ssh
find . -name '*.pyc' -delete
測試
命令行執行 make clean便可 ui
官網 http://www.fabfile.org/ this
入門文檔 http://docs.fabfile.org/en/1.10/tutorial.html spa
舉個栗子~
#!/usr/bin/env python # encoding: utf-8 ''' makefile的fabfile移植版 ''' from fabric.api import run, cd, settings, abort, env from fabric.contrib.console import confirm class DeployClass(): ''' 部署腳本 ''' def init_constant(self, *arg): ''' 初始化常量 ''' self.PREFIX_PATH = '/data/www/' self.ALL_PATH = [self.PREFIX_PATH + i.strip() for i in arg if i] self.CTL = 'supervisorctl -s unix:///tmp/supervisor.sock ' def update(self, *arg): ''' 更新當前分支下代碼 ''' # 初始化 self.init_constant(arg) # 校驗並去除無效路徑 self.pre_test() for project_path in self.ALL_PATH: with cd(project_path): branch = self._get_current_branch() if not branch: continue run('git pull origin %s' % branch) def oper_supervisor(self, action, no_start, no_end, prefix): ''' 多進程服務操做(start/stop/restart) :params action 操做 :params no_start 進程編號起 :params no_end 進程編號止 :params prefix 進程名稱前綴 ''' assert action in ('start', 'stop', 'restart') self.init_constant() for no in range(int(no_start), int(no_end)+1): cmd = '%s %s%s' % (action, prefix, no) run('%s %s' % (self.CTL, cmd)) def oper_supervisor_multi(self, action, *process): ''' 多進程服務操做(start/stop/restart) :params action 操做 :params process 進程名稱,... ''' assert action in ('start', 'stop', 'restart') self.init_constant() for pro in process: cmd = '%s %s' % (action, pro) run('%s %s' % (self.CTL, cmd)) @staticmethod def _get_current_branch(): ''' 獲取當前路徑下的分支名稱 ''' # res = run("git branch|grep '^\*'|awk -F'*' 'print {$2}'") with settings(warn_only=True): print '------------update[%s]start-----------' % run('pwd') res = run('git branch') if res.failed: if confirm('[%s] is not a git rep, want exit?' % run('pwd')): abort('ok, you stop it !') else: return None branch = run("git branch|grep '^\*'|awk -F'*' '{print $2}'") return branch def pre_test(self): ''' 先行測試 ''' print '------------>all_path-----------%s'% self.ALL_PATH with settings(warn_only=True): # 測試路徑是否合法 for _path in self.ALL_PATH: res = run('test -d %s' % _path) if res.failed: if confirm('[%s] not exist! end this?' % _path): abort('ok, you stop it !') else: print '============rm path [%s]================' % _path self.ALL_PATH.remove(_path) # 繼續執行時,剔除無效路徑 DC = DeployClass() def update(*arg): ''' 更新 ''' DC.update(*arg) def oper_supervisor(action, no_start, no_end, prefix): ''' 操做項目的多個進程 ''' DC.oper_supervisor(action, no_start, no_end, prefix) def oper_supervisor_multi(action, *process): ''' 操做多個進程的項目 ''' DC.oper_supervisor_multi(action, *process)