python运维之fabric

随着云、大数据的快速发展,应用需要进行分布式部署,少则部署在数十台主机,多则部署在成百上千台主机。

如果认为进行应用部署、上传、启动等管理,则会非常困难,且容易出错,作为运维的福音,fabric将会解决这些问题,让运维更加容易、方便。


1、首先需要安装fabric,python版本要求2.7以上。

pip install fabric

或者

easy_install fabric

或者下载源码

python setup.py install

为了在任何路径能够执行fab,需要把fab的路径加入到PATH环境变量里面


2、第一个fab文件,创建fabfile.py文件,因为fab命令默认执行当前路径的fabfile文件,如果不是此命名的文件,需要加选项执行  fab -f myfab.py hello

def hello():

     print "hello fabric"


fab hello

另外可以用fab -l 查看所有的任务

且支持传入参数

def hello(name):

     print(“hello %s” % name)

执行命令  fab hello:name=test


3、执行本地命令

def  mylocal():

     local('ls -al /etc')

这样结果输出到stdout,但是有时我们需要把输出结果到变量里面,进行相应的处理

def mylocal():

    outmsg = local('ls -al /etc',capture=True)

capture默认是False


4、执行远程主机命令

env.host=192.168.1.128

env.user=test

env.password=test

def myremote():

      run('uname -a')


如果是多台主机可以用

env.hosts=['192.168.1.128','192.168.1.129']

程序会串行在两台主机上执行对应的命令

也可以通过-H命令来传如主机列表

fab -H 192.168.1.130,192.168.1.131 myremote


5、在实际情况中,主机用户、密码、ip各不相同,可以采用角色的方式来处理

from fabric.api import *

env.roledefs = {'eai':['[email protected]','[email protected]'],'idmm':['[email protected]','[email protected]']}

env.passwords = {‘eai’:'Eai','idmm':'idmm'}

@roles('eai')
def test0():
    run('uname -a')

@roles('idmm')
def test1():
    run('hostname')

def task():

    execute(test0)

    execute(test1)

执行:fab task

但是此时发现需要输入命令,查了很多资料发现env.passwords的定义方式没有问题,最后只能翻源码看了,发现env.passwords定义方式变了,需要采用如下方式

env.passwords = {"[email protected]:22":"Eai","[email protected]:22":"Eai","[email protected]:22":"idmm","[email protected]:22":"idmm"}

这是我使用的版本

Fabric 1.14.0
Paramiko 2.0.0

另外可以用-R方式来执行任务的组

fab -R eai test1


6、上传文件

put(local,remote)

def myput():
    put('/Eai/work/fab/fabfile.py','/Eai')


7、下载文件

get(remote,local)

def myget():
    get('/Eai/DtServ/1.py','/Eai/work/fab/1.py')


8、交互输入

def mycommand():
    cmd = prompt('please input your cmd:')
    run(cmd)


9、上线文管理

with cd设置远端主机的目录


def mywith():
    with cd('/Eai/work'):
        put('/Eai/work/fab/fabfile.py','x.py')


path: 添加远程机的PATH路径

with path('/home/zt/python/bin'):


settings: 设置Fabric环境变量参数

with settings(warn_only=True):


shell_env: 设置Shell环境变量

withshell_env(PYTHONHOME='/opt/python2712'):


prefix: 设置命令执行前缀

def myprefix():
    with prefix("hostname"):
         local('uname -a')
         local('pwd')



10、错误处理,遇到错误不退出

env . warn_only = True
或者

fab -w myput


11、并行处理
fab -P myput
或者
env . parallel = True

或者parallel装饰的并行,serially的为串行
@ parallel
def runs_in_parallel ( ) :
     pass
@serially
def runs_serially ( ) :
     pass

12、只运行一次,通过runs_once装饰
@ runs_once
def hello ( ) :
     print "Hello Fabric!"
def test ( ) :
     execute ( hello )
     execute ( hello )



猜你喜欢

转载自blog.csdn.net/zt3032/article/details/78170026