fabric 自动化部署 python

1、安装python-devel yum install python-devel

2、pip python安装管理
       a、下载安装setuptools包 curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
            python ez_setup.py
       b、下载安装pip包 curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
             python get-pip.py

3、安装fabric pip install fabric
          如果出现encode异常设置 /usr/bin/pip添加 sys.setdefaultencoding('utf8')

http://docs.fabfile.org/en/1.4.0/index.html
Fabric是一个Python库,可以通过SSH在多个host上批量执行任务。你可以编写任务脚本,然后通过Fabric在本地就可以使用SSH在大量远程服务器上自动运行。这些功能非常适合应用的自动化部署,或者执行系统管理任务。
让我们首先看一个例子。我们知道在*NIX下面,uname命令是查看系统的发行版。可以写这样一个Fabric脚本:
from fabric.api import run
def host_type():
    run('uname -s')


=====================================================

Python fabric实践操作
前面学习了理论,下面该练练手了。两台机器:10.1.6.186、10.1.6.159。fabric部署在10.1.6.186上面。

1  执行一个简单的task任务,显示两台机器的/home/guol/目录下的文件
#!/usr/bin/python
from fabric.api import *
from fabric.context_managers import *


env.hosts=['10.1.6.186','10.1.6.159']
env.password='xxxxxx'


def task1():
    with cd('/home/guol'):
        run('ls -l')


##结果
root@vm11:/tmp# fab task1
[10.1.6.186] Executing task 'task1'
[10.1.6.186] run: ls -l
[10.1.6.186] out: total 0
[10.1.6.186] out: -rw-r--r-- 1 root root 0 Dec 21 13:32 186-local
[10.1.6.186] out:

[10.1.6.159] Executing task 'task1'
[10.1.6.159] run: ls -l
[10.1.6.159] out: total 0
[10.1.6.159] out: -rw-r--r-- 1 root root 0 Dec 21 13:32 159-remote
[10.1.6.159] out:


Done.
Disconnecting from 10.1.6.159... done.
Disconnecting from 10.1.6.186... done.


2  执行和1相同的任务,不过排除掉10.1.6.159这台机器
#!/usr/bin/python
from fabric.api import *
from fabric.context_managers import *


env.hosts=['10.1.6.186','10.1.6.159']
env.password='xxxxxx'

env.exclude_hosts=['10.1.6.159']


def task1():
    with cd('/home/guol'):
        run('ls -l')


##执行
root@vm11:/tmp# fab task1
[10.1.6.186] Executing task 'task1'
[10.1.6.186] run: ls -l
[10.1.6.186] out: total 0
[10.1.6.186] out: -rw-r--r-- 1 root root 0 Dec 21 13:32 186-local
[10.1.6.186] out:




Done.
Disconnecting from 10.1.6.186... done.


更多请看:http://www.fabfile.org/

猜你喜欢

转载自j2ee-yohn.iteye.com/blog/2312080