项目发布和运维的工做至关机械,频率还蛮高,致使时间浪费在敲大量重复的命令上。python
修复bug什么的,测试,提交版本库(2分钟),ssh到测试环境pull部署(2分钟),rsync到线上机器A,B,C,D,E(1分钟),分别ssh到ABCDE五台机器,逐一重启(8-10分钟) = 13-15分钟git
其中郁闷的是,每次操做都是相同的,命令同样,要命的是在多个机器上,很难在本机一个脚本搞定,主要时间都浪费在ssh,敲命令上了,写成脚本,彻底能够一键执行,花两分钟看下执行结果。ubuntu
pip install fabricapi
#fabfile.py from fabric.api import run def host_type(): run('uname -s')
启动运维
itcast@ubuntu:~/tmp/fab$ fab -H 127.0.0.1 host_type
[127.0.0.1] Executing task 'host_type' [127.0.0.1] run: uname -s [127.0.0.1] Login password for 'itcast': [127.0.0.1] out: Linux [127.0.0.1] out: Done. Disconnecting from 127.0.0.1... done. itcast@ubuntu:~/tmp/fab$ fab -H 127.0.0.1 host_type [127.0.0.1] Executing task 'host_type' [127.0.0.1] run: uname -s [127.0.0.1] Login password for 'itcast': [127.0.0.1] out: Linux [127.0.0.1] out:
from fabric.api import * env.hosts=['192.168.17.192', '192.168.17.193'] #env.password='python' env.passwords = { 'itcast@192.168.17.192:22':'python', 'itcast@192.168.17.193:22':'python', } @runs_once def input_raw(): return prompt("please input directory name:", default="/home") def workask(dirname): run('ls -l ' + dirname) @task def go(): print('start ...') getdirname = input_raw() workask(getdirname) print('end ...')
from fabric.api import * env.user = 'itcast' env.hosts = ['192.168.17.192', '192.168.17.193'] env.password = 'python' @task @runs_once def tar_task(): with lcd('/home/itcast/testdemo'): local('tar zcvf demo.tar.gz demo.py') @task def put_task(): run('mkdir -p /home/itcast/testdemo') with cd('/home/itcast/testdemo'): put('/home/itcast/testdemo/demo.tar.gz', '/home/itcast/testdemo/demo.tar.gz') @task def check_task(): lmd5 = local('md5sum /home/itcast/testdemo/demo.tar.gz', capture=True).split(' ')[0] rmd5 = run('md5sum /home/itcast/testdemo/demo.tar.gz').split(' ')[0] if lmd5 == rmd5: print('OK ...') else: print('ERROR ...') @task def run_task(): with cd('/home/itcast/testdemo'): run('tar zxvf demo.tar.gz') run('python demo.py') @task def go(): tar_task() put_task() check_task() run_task()
from fabric.api import * env.user = 'itcast' env.hosts = ['192.168.17.192', '192.168.17.193'] env.password = 'python' @runs_once @task def local_update(): with lcd("/home/itcast/tmp/itcasthello"): local("git add -A") local("git commit -m 'update'") local("git pull origin master") local("git push origin master") @task def remote_update(): with cd("/home/itcast/tmp/itcasthello"): run("git checkout master") run("git pull origin master") @task def deploy(): local_update() remote_update()