abric是基于Python实现的SSH命令行工具,简化了SSH的应用程序部署及系统管理任务,它提供了系统基础的操作组件,可以实现本地或远程shell命令,包括:命令执行、文件上传、下载及完整执行日志输出等功能。Fabric在Paramiko的基础上做了更高一层的封装,操作起来会更加简单
安装时候需要安装一些依赖包 setuptools-18.5 paramiko-2.4.1 pycrypto-2.6.1 Fabric-1.8.2
wget https://files.pythonhosted.org/packages/ec/6d/b433a14c77ad17b917a9646d5ac96275309170a88fcffc967def7a1ba8ce/setuptools-18.5.tar.gz
wget https://files.pythonhosted.org/packages/ab/82/4cd6cbb2001431aece679c5c496bb49d2094f10e9cc98b9f94fa7261a935/Fabric-1.8.2.tar.gz
wget https://files.pythonhosted.org/packages/60/db/645aa9af249f059cc3a368b118de33889219e0362141e75d4eaf6f80f163/pycrypto-2.6.1.tar.gz
wget https://files.pythonhosted.org/packages/29/65/83181630befb17cd1370a6abb9a87957947a43c2332216e5975353f61d64/paramiko-2.4.1.tar.gz
全部解压安装 python setup.py install
命令格式:
fab [options][:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
常用参数:
-l #显示定义好的任务函数名 -f #指定fab入口文件,默认入口文件名为fabfile.py -f #指定网关(中转)设备,比如堡垒机环境,填写堡垒机IP即可 -H #指定目标主机,多台主机用‘,’号分隔 -p #远程账号的密码,fab执行时默认使用root账户 -P #以异步并行方式运行多主机任务,默认为串行运行 -R #指定role(角色),以角色名区分不同业务组设备 -t #设置设备连接超时时间(秒) -T #设置远程主机命令执行超时时间(秒) -w #当命令执行失败,发出警告,而非默认中止任务。
示例:test.py
#!/usr/bin/env python # -*- coding:utf-8 -*- from fabric.api import run #定义一个任务函数,通过run方法实现远程执行‘uname -s’命令 def host_type(): run('uname -s')
fab操作命令:
fab -H localhost host_type fab -p 123456 -H localhost -- 'uname -s'
fabfile文件编写
env对象:
env.hosts #定义目标主机,可以用IP或主机名表示,以python的列表形式定义。如env.hosts=['192.168.1.21','192.168.1.22'] env.exclude_hosts #排除指定主机,如env.exclude_hosts=['192.168.1.21'] env.user #定义用户名,如env.user='root' env.port #定义端口,默认为22,如env.port='22' env.password #定义密码,如env.password='123456' env.passwords #定义多个密码,不同主机对应不同密码,如:env.passwords = {'[email protected]:22':'123456','[email protected]:22':'654321'} env.gateway #定义网关(中转、堡垒机)IP,如env.gateway='192.168.1.23 env.roledefs #定义角色分组,比如web组合db组主机区分开来:env.roledefs = {'webserver':['192.168.1.21','192.168.1.22'],'dbserver':['192.168.1.25','192.168.1.26']} env.deploy_release_dir #自定义全局变量,格式:env. + '变量名称',如env.age,env.sex等
env.roledefs的使用方法实例:
env.roledefs = {'webserver':['192.168.1.21','192.168.1.22'],'dbserver':['192.168.1.25','192.168.1.26']} #引用分组时使用python装饰器方式来进行,如: @roles('webserver') def webtask(): run('/usr/local/nginx/sbin/nginx') @roles('webserver','dbserver') def publictask(): run('uptime')
fabric常用api
local #执行本地命令,如local('uname -s') lcd #切换本地目录,如lcd('/home') cd #切换远程目录 run #执行远程命令 sudo #sudo方式执行远程命令,如sudo('/etc/init.d/httpd start') put #上次本地文件导远程主机,如put('/home/user.info','/data/user.info') get #从远程主机下载文件到本地,如:get('/data/user.info','/home/user.info') prompt #获得用户输入信息,如:prompt('please input user password:') confirm #获得提示信息确认,如:confirm('Test failed,Continue[Y/N]?') reboot #重启远程主机,如:reboot() @task #函数修饰符,标识的函数为fab可调用的,非标记对fab不可见,纯业务逻辑 @runs_once #函数修饰符,标识的函数只会执行一次,不受多台主机影响
fabric应用示例:
示例1:查看本地与远程主机信息 fab -f test.py local_task fab -f test.py remote_task
#!/usr/bin/env python # -*- encoding: utf-8 -*- from fabric.api import * env.user = 'root' env.hosts = ['192.168.1.22'] env.password = '123456' @runs_once #查看本地系统信息,当有多台主机时只运行一次 def local_task(): #本地任务函数 local('uname -a') def remote_task(): with cd('/var/logs'): #with的作用是让后面的表达式语句继承当前状态,实现:cd /var/logs && ls -l的效果 run('ls -l')
示例2:动态获取远程目录列表 fab -f test.py go
#!/usr/bin/env python # -*- coding: utf-8 -*- from fabric.api import * env.user = 'root' env.hosts = ['192.168.1.22'] env.password = '123456' @runs_once #主机遍历过程中,只有第一台触发此函数 def input_raw(): return prompt('please input directoryname:',default='/root') def worktask(dirname): run('ls -l'+dirname) @task #限定只有go函数对fab命令可见,其他没有使用@task标记的函数fab命令不可用 def go(): getdirname = input_raw() worktask(getdirname)
示例3:网关模式文件上传与执行(中转,堡垒机) fab -f test.py go
#!/usr/bin/env python # -*- encoding: utf-8 -*- from fabric.api import * from fabric.context_managers import * from fabric.contrib.console import confirm env.user = 'root' env.gateway = '192.168.1.23' #定义堡垒机IP,作为文件上传、执行的中转设置 env.hosts = ['192.168.1.21','192.168.1.22'] env.passwords = { '[email protected]:22':'123456', '[email protected]:22':'abcdef', '[email protected]:22':'123abc', #堡垒机账号信息 } lpackpath = '/home/install/lnmp.tar.gz' #本地安装包路径 rpackpath = '/tmp/install' #远程安装包路径 @task def put_task(): #上传文件 run('mkdir -p /tmp/install') #默认情况下,当命令执行失败时,Fabric会停止执行后续命令。有时,我们允许忽略失败的命令继续执行,比如run(‘rm /tmp/abc')在文件不存在的时候有可能失败,这时可以用with settings(warn_only=True):执行命令,这样Fabric只会打出警告信息而不会中断执行。 with settings(warn_only=True): result = put(lpackpath,rpackpath) #上传 if result.failed and not confirm('put file failed,Continue[Y/N]?'): abort('Aborting file put task!') @task def run_task(): #安装 with cd('/tmp/install'): run('tar -zxvf lnmp.tar.gz') with cd('lnmp/'): #使用with继承/tmp/install目录位置状态 run('./centos.sh') @task def go(): #上传、安装组合命令 put_task() run_task()
示例4:文件的打包上传和校验
#!/usr/bin/env python # -*- coding: utf-8 -*- from fabric.api import * from fabric.context_managers import * from fabric.contrib.console import confirm env.user = 'root' env.hosts = ['192.168.1.23','192.168.1.24'] env.password = '123456' @task @runs_once def tar_task(): with lcd("/data/logs"): local("tar zcf logs.tar.gz test.log") @task def put_task(): run('mkdir -p /data/logs') with cd("/data/logs"): with settings(warn_only=True): result=put("/data/logs/logs.tar.gz","/data/logs/logs.tar.gz") if result.failed and not confirm("put file failed,Continue[Y/N]?"): abort('Aborting file put task') @task def check_task(): with settings(warn_only=True): lmd5=local("md5sum /data/logs/logs.tar.gz",capture=True).split(' ')[0] rmd5=run("md5sum /data/logs/logs.tar.gz").split(' ')[0] if lmd5==rmd5: print "OK" else: print "ERROR" def go(): tar_task() put_task() check_task() fab -f test.py go
示例5:部署lnmp环境
#!/usr/bin/env python # -*- coding: utf-8 -*- from fabric.colors import * from fabric.api import * env.user='root' env.roledefs={ 'webservers': ['192.168.1.21','192.168.1.22'], 'dbservers': ['192.168.1.23'] } env.passwords={ '[email protected]:22':'123456', '[email protected]:22':'asdfgh', '[email protected]:22':'654321' } @roles('webservers') def web_task(): print yellow("install nginx php php-fpm....") with settings(warn_only=True): run("yum install -y nginx") run("yum install -y php-fpm php-mysql php-mbstring php-xml php-mcrypt php-gd") run("systemctl enable php-fpm") run("systemctl enable nginx") @roles(dbservers) def db_task(): print yellow("install mysql...") with settings(warn_only=True): run("yum install -y mariadb mariadb-server") run("systemctl enable mariadb") @roles('webservers','dbservers') def pub_task(): print yellow("install ntp....") with settings(warn_only=True): run("yum install epel-release -y") run("yum install ntp -y ") def deploy(): execute(pub_task) execute(web_task) execute(db_task) fab -f test.py deploy
示例:6:生产环境代码发布管理 (打包 发布 回滚)
#!/usr/bin/env python # -*- coding: utf-8 -*- from fabric.api import * from fabric.colors import * from fabric.context_managers import * from fabric.contrib.console import confirm import time env.hosts=['192.168.1.21','192.168.1.22'] env.user='root' env.password='124530' env.project_dev_source='/data/dev/webadmin/' env.project_tar_source='/data/dev/releases/' env.project_pack_name='release' env.deploy_project_root='/data/www/webadmin/' env.deploy_release_dir='releases' env.deploy_current_dir='current' env.deploy_version=time.strftime("%Y-%m-%d")+"v2" @runs_once def input_version(): return prompt("please input your roolback version ID ",default="") @task @runs_once def tar_source(): print yellow("creating source package....") with lcd(env.project_dev_source): local("tar -zcf %s.tar.gz ." % (env.project_tar_source + env.project_pack_name)) print green("creating source package success!") @task def put_package(): print yellow("start put package....") with settings(warn_only=True): with cd(env.deploy_project_root+env.deploy_release_dir): run("mkdir %s" % (env.deploy_version)) env.deploy_full_path=env.deploy_project_root + env.deploy_release_dir + "/" +env.deploy_version with settings(warn_only=True): result=put(env.project_tar_source+env.project_pack_name+".tar.gz",env.deploy_full_path) if result.failed and not ("put file failed,Continue[Y/N]?"): abort('Aborting file put task') with cd(env.deploy_full_path): run("tar -zxf %s.tar.gz" % (env.project_pack_name)) run("rm -rf %s.tar.gz" % (env.project_pack_name)) print green("put & untar package success!") @task def make_symlink(): print yellow("update current symlink") env.deploy_full_path=env.deploy_project_root + env.deploy_release_dir + "/" +env.deploy_version with settings(warn_only=True): run("rm -rf %s" % (env.deploy_project_root+env.deploy_current_dir)) run("ln -s %s %s" % (env.deploy_full_path,env.deploy_project_root+env.deploy_current_dir)) print green("make symlink success!") @task def roolback(): print yellow("roolback project version") versionid=input_version() if versionid=='': abort("project version Id error,abort!") env.deploy_full_path=env.deploy_project_root + env.deploy_release_dir + "/" +versionid run("rm -f %s" % (env.deploy_project_root+env.deploy_current_dir)) run("ln -s %s %s" % (env.deploy_full_path,env.deploy_project_root+env.deploy_current_dir)) print green("roolback success!") @task def go(): tar_source() put_package() make_symlink() 生产nginx目录配置 root /data/www/webadmin/current;