fabric应用

安装: easy_install fabric 或 pip install fabric  

验证:

#python

>>> import  fabric

有时候我们可以直接使用命令行的形式执行:

#fab -p rootroot -H 10.1.1.21,10.1.1.22 -- 'uname -s' 

fab命令引用默认的文件名为 fabfile.py 如果使用非默认文件名称,则需通过 "-f" 来指定。如果管理机与目标主机未配置密钥认证信任,将会提示输入目标主机对应账号登录密码。

Fabric提供几个简单的API来完成所有的部署,最常用的是local()和run(),分别在本地和远程执行命令,put()可以把本地文件上传到远程,当需要在远程指定当前目录时,只需用with cd('/path/to/dir/'):即可。

默认情况下,当命令执行失败时,Fabric会停止执行后续命令。有时,我们允许忽略失败的命令继续执行,比如run('rm /tmp/abc')在文件不存在的时候有可能失败,这时可以用

with settings(warn_only=True):执行命令,这样Fabric只会打出警告信息而不会中断执行

Fabric是如何在远程执行命令的呢?其实Fabric所有操作都是基于SSH执行的,必要时它会提示输入口令,所以非常安全。更好的办法是在指定的部署服务器上用证书配置无密码的ssh连接。

常用API:

local  执行本地命令,如:local('uname -s')

lcd     切换本地目录,如:lcd('/home')

cd     切换远程目录

run    执行远程命令,如run('free -m')

sudo  sudo方式执行远程命令,如sudo('/etc/init.d/httpd start')

put    上传本地文件到远程主机,如put('/home/user.info', '/data/user.info')

get    从远程主机下载文件到本地,如get('/data/user.info', '/home/root.info')

prompt  获得用户输入信息,如prompt('please input your ID:')或prompt('please input uour ID:',default='123' )

confirm  获得提示信息确认,如confirm("Test failed.Continue[Y/N]?")。  当 if confirm("Continue [Y/N]?")时,输入Y/y表示为真,条件成立。

reboot   重启远程主机,如reboot()

@task   函数修饰符,标识的函数为fab可调用的,非标记对fab不可见,纯业务逻辑

@runs_once  函数修饰符,标识的函数只会执行一次,不受多台主机影响

-------------------------------------------------------------------------------------------

set命令相关:

功能说明:
        设置shell

语  法:
        set [+-abCdefhHklmnpPtuvx]

补充说明:
set指令能设置所使用shell的执行方式,可依照不同的需求来做设置。

参  数:
        -a  标示已修改的变量,以供输出至环境变量。 
        -b  使被中止的后台程序立刻回报执行状态。 
        -C  转向所产生的文件无法覆盖已存在的文件。 
        -d  Shell预设会用杂凑表记忆使用过的指令,以加速指令的执行。使用-d参数可取消。 
        -e  若指令传回值不等于0,则立即退出shell。   
        -f   取消使用通配符。 
        -h  自动记录函数的所在位置。 
        -H Shell  可利用"!"加<指令编号>的方式来执行history中记录的指令。 
        -k  指令所给的参数都会被视为此指令的环境变量。 
        -l  记录for循环的变量名称。 
        -m  使用监视模式monitor,允许作业控制。 
        -n  只读取指令,而不实际执行。 
        -p  启动优先顺序模式。 
        -P  启动-P参数后,执行指令时,会以实际的文件或目录来取代符号连接。 
        -t  执行完随后的指令,即退出shell。 
        -u  当执行时使用到未定义过的变量,则显示错误信息。 
        -v  显示shell所读取的输入值。 
        -x  执行指令后,会先显示该指令及所下的参数。 
        +<参数>  取消某个set曾启动的参数。 

Finally, I was able to figure out how to startup tomcat remotely with fabric.

The issue was in background tasks as they will be killed when the command ends.

The solution is simple: just add "set -m;" prefix before command. The full fabric command should be:

sudo('set -m; /opt/tomcat/bin/startup.sh')
例如:
#!/usr/bin/python
#coding:utf-8
from fabirc.api import *
from fabric.colors import *
#env.hosts=['10.1.1.42']
env.roledefs = { #当采用角色组时,注意定义go时,要使用execute()
'myhost': ['10.1.1.42','10.1.1.43'],
'myhost2': ['10.1.1.43']
} env.user='root' env.tomcatpath='/yly/tomcat7.callback80' @roles('myhost') def shutdowntomcat(): with cd(env.tomcatpath): with settings(warn_only=True): run("ps -ef|grep tomcat|grep -v 'grep'|grep callback|awk '{print $2}'|xargs kill -9") run("rm -fr ./logs/*;rm -fr ./work/*") print green ("41 tomcat for callback already shutdown! ")

@roles('myhost')
def shut_tom():
    with cd(env.project_ss):
    result=local('touch /tmp/jiajia')
    if result.failed and not confirm("continue away?"):   #此处not confirm表示当输入n
    run("touch /tmp/jiajia222")

@roles('myhost2')
def starttomcat():
    with cd(env.tomcatpath):
        with settings(warn_only=True):
            run("set -m ; sh ./bin/startup.sh")
        print yellow ("41 tomcat for callback already started!")

@task #限定只有go函数对fab命令可见,其它shut_tom、starttomcat则无法使用fab调用。当去掉@task时,或每个函数都加上@task时方可调用所有已有函数。
def go():
execute(shutdownmytomcat)
execute(shut_tom)
execute(starttomcat)

参考资料:http://fabric-chs.readthedocs.org/zh_CN/chs/

              http://paperplane.ruhoh.com/fabric/fabric-api/

原文地址:https://www.cnblogs.com/wjoyxt/p/5009505.html