一、简介

Fabric是基于Python 2.5及以上版本实现的SSH命令行工具,简化了SSH了应用程序部署及系统管理任务,它提供了系统基础的操作组件,可以实现本地或远程shell命令,包括命令执行文件上传下载及完整执行日志输出等功能。Fabric在paramiko的基础上做了更高一层的封装,操作起来会更简单.


Fabric官方文档:http://www.fabfile.org/

API文档:http://docs.fabfile.org/en/1.10/

基础案例文档:http://docs.fabfile.org/en/1.10/tutorial.html

Fabric中文文档:http://fabric-docs-cn.readthedocs.org/zh_CN/latest/


二、安装

(1) 安装epel源
rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
sed -i 's/^#//' /etc/yum.repos.d/epel.repo
sed -i 's/mirrorlist/#mirrorlist/' /etc/yum.repos.d/epel.repo

(2)安装依赖包
yum install gcc gcc-c++ python-devel openssl-devel openssl zlin zlib-devel -y

(3)安装pip
yum install python-pip -y

(4)安装fabric
pip install fabric

(5)测试fabric是否安装正确
python -c 'import fabric'


三、Fabric的应用

注意事项:fab命令引用默认文件名为fabfile.py,如果使用非默认文件名称,则需要通过-f来执行,如

fab -H 192.168.1.100,192.168.1.105 -f host_type.py host_type

如果管理机与目标主机未配置秘钥认证信任,将会提示输入目标主机对应账号登录密码。

fab作为fabric程序的命令行入口,提供了丰富的参数调用


工作中的应用场景:由于目前我们用的都是云平台,比如阿里云、腾讯云、之前还用过一段时间的ucloud等等,用起来效果还是挺好的,有时候为了更方便的管理,对系统进行优化,安装一些agent(zabbix,saltstack,network等),这个时候我们就可以用fabric进行操作,感觉效果挺好的。

由于fabric是单线程工作的,之前我想将其改成多线程,但是没有成功,如果有朋友应该怎么修改,也请麻烦告诉我一声,谢谢啦,多交朋友多脉圈,哈哈


在这里分享一个febric的脚本

#!/usr/bin/env python
#encoding: utf-8

from fabric.api import *  
from fabric.colors import *
from fabric.context_managers import *  
from fabric.contrib.console import confirm  
import os
  
#定义目标主机信息  
env.user='root'  
env.hosts=['192.168.0.141',]  
env.password='redhat'  

#定义目录结构
LocalDir = "/home/saltroot/gameroot"
RemoteDir = "/home/saltclient/gameroot/"
LocalFile = os.path.join(LocalDir,"script.tar.gz")
RemoteFile = os.path.join(RemoteDir,"script.tar.gz")
 
#打包文件  
def tar_task():  
    with lcd(LocalDir):  
        local("tar -zcf script.tar.gz script")  
  
#上传文件  
def put_task():  
    run("mkdir -p %s" % RemoteDir)
    with settings(warn_only=True):  		#put上传出现异常时继续执行,非终止
        result = put(LocalFile,RemoteFile)  
    if result.failed and not confirm("put file failed, Continue[Y/N]?"):  
        abort("Aborting file put task!")  	#出现异常时,确认是否继续,(Y继续)
  
#校对文件  
def check_task():  
    with settings(warn_only=True):  
        lmd5=local("md5sum %s" % LocalFile,capture=True).split(' ')[0]  
        rmd5=run("md5sum %s" % RemoteFile).split(' ')[0]  
    if lmd5==rmd5:  				#对比本地及远程文件的md5信息
        print yellow("OK")
    else:  
        print red("ERROR")

#初始化
def agent_task():
    with cd(RemoteDir):
        run("tar -zxf script.tar.gz")
        with cd("script/"):
    	    run("./init.sh")

#4个功能一起实现  
@task  						#限定只有go函数对fab可见
def go():  
    print yellow("program start ...")
    tar_task()  
    put_task()  
    check_task()  
    agent_task()
    print green("program sucessful ...")

    
############################################
# 命令执行方式
# fab go
# 额外的命令
# @roles('new') 
# def show():
#    print green('success')
#    print red('fail')
#    print yellow('yellow')
#定义业务角色
#env.user='root'  
#env.roledefs = {
#    'new': ['192.168.0.100',],
#    'ios': ['192.168.0.130','192.168.0.101'],
#    'Andorid': ['192.168.0.200', '192.168.0.201', '192.168.0.230']
#}
#
#env.passwords = {
#    'root@192.168.0.100:22': 'redhat',
#    'root@192.168.0.120:22': 'redhat'
#}
############################################