Python 远程部署利器 Fabric 详解

From:http://python.jobbole.com/87241/

From:Python模块学习 - fabric(Python3):https://www.cnblogs.com/xiao-apple36/p/9124292.html

fabric 官网英文文档:http://www.fabfile.org/

fabric 中文站点:http://fabric-chs.readthedocs.io/zh_CN/chs/

python三大神器之一fabric使用:https://www.cnblogs.com/rufus-hua/p/5144210.html

如何用Fabric实现无密码输入提示的远程自动部署:https://blog.csdn.net/slvher/article/details/50414675

fabric实现远程操作和部署:http://python.jobbole.com/83716/

自动化运维管理 fabric:http://www.ttlsa.com/python/automation-operation-and-maintenance-tool-fabric/

Python3自动化运维之Fabric模版详解:https://www.imooc.com/article/38448

《Python自动化运维技术与最佳实践》

简介

Fabric 是一个 Python 的库,同时它也是一个命令行工具。它提供了丰富的同 SSH 交互的接口,可以用来在本地或远程机器上自动化、流水化地执行 Shell 命令。使用 fabric 提供的命令行工具,可以很方便地执行应用部署和系统管理等操作。因此它非常适合用来做应用的远程部署及系统维护。其上手也极其简单,你需要的只是懂得基本的 Shell 命令。

fabric 依赖于 paramiko 进行 ssh 交互,fabric 的设计思路是通过几个 API 接口来完成所有的部署,因此 fabric 对系统管理操作进行了简单的封装,比如执行命令,上传文件,并行操作和异常处理等。

paramiko 是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,fabric 和 ansible 内部的远程管理就是使用的paramiko来现实。

Fabric是一个用于应用(批量)部署和系统(批量)管理的Python库和命令行工具,关于Fabric的介绍请参考:http://www.fabfile.org/。  Capistrano是一个用Ruby语言编写的远程服务器自动化和部署工具,关于Capistrano的介绍请参考:http://capistranorb.com/

  本文仅使用Python语言和部分Linux或Windows系统命令,借助Fabric模块和Capistrano的部署思路,实现在Linux平台和Windows平台的自动化部批量署应用或实现批量系统管理(批量执行命令,批量上传文件等),其中Fabric部分利用Fabric的模块,Capistrano部分用Python语言按照Capistrano的部署思路“重写(Python实现Capistrano)”。
  关于Capistrano的“重写”说明。Capistrano使用Ruby语言写的,在部署很多应用上有很大的优势,个人认为它设计最好的部分就是它的目录结构。目录结构的详细信息可以参考:http://capistranorb.com/documentation/getting-started/structure/#。有了这个目录结构可以轻松实现每一个部署版本的备份与回滚,之前用Bash Shell“重写”过一次,可以参考本文《Linux Shell脚本之远程自动化部署java maven项目 》,这次相当于用Python重写一下(Capistrano还有大量精髓的东西,本文算是抛砖引玉,其他的日后再发掘),毕竟Shell脚本不容易实现像Fabric那样的批量操作。

安装Fabric

Fabric的官网是 www.fabfile.org,源码托管在Github上。你可以clone源码到本地,然后通过下面的命令来安装。

python setup.py develop

在执行源码安装前,你必须先将Fabric的依赖包Paramiko装上。所以,个人还是推荐使用pip安装,只需一条命令即可:

pip install fabric

python3 安装时使用的是fabric3 :( 安装fabric3之前,需要先卸载fabric。) 

 
  1. # fabric3 支持 python3

  2. pip uninstall fabric

  3. pip3 install fabric3

由于 fabric 不只是一个Python 模块,fabric 还是一个命令行工具,可以通过 help 进行命令的了解

 
  1. [king@ubuntu]$ fab -V

  2. Fabric 2.2.0

  3. Paramiko 2.4.1

  4. Invoke 1.1.0

  5. [king@ubuntu]$ fab -h

  6. Usage: fab [--core-opts] task1 [--task1-opts] ... taskN [--taskN-opts]

  7.  
  8. Core options:

  9.  
  10. --complete Print tab-completion candidates for given parse remainder.

  11. --hide=STRING Set default value of run()'s 'hide' kwarg.

  12. --no-dedupe Disable task deduplication.

  13. --prompt-for-login-password Request an upfront SSH-auth password prompt.

  14. --prompt-for-passphrase Request an upfront SSH key passphrase prompt.

  15. --prompt-for-sudo-password Prompt user at start of session for the sudo.password config value.

  16. --write-pyc Enable creation of .pyc files.

  17. -c STRING, --collection=STRING Specify collection name to load.

  18. -d, --debug Enable debug output.

  19. -D INT, --list-depth=INT When listing tasks, only show the first INT levels.

  20. -e, --echo Echo executed commands before running.

  21. -f STRING, --config=STRING Runtime configuration file to use.

  22. -F STRING, --list-format=STRING Change the display format used when listing tasks. Should be one of: flat (default),

  23. nested, json.

  24. -h [STRING], --help[=STRING] Show core or per-task help and exit.

  25. -H STRING, --hosts=STRING Comma-separated host name(s) to execute tasks against.

  26. -i, --identity Path to runtime SSH identity (key) file. May be given multiple times.

  27. -l [STRING], --list[=STRING] List available tasks, optionally limited to a namespace.

  28. -p, --pty Use a pty when executing shell commands.

  29. -r STRING, --search-root=STRING Change root directory used for finding task modules.

  30. -S STRING, --ssh-config=STRING Path to runtime SSH config file.

  31. -V, --version Show version and exit.

  32. -w, --warn-only Warn, instead of failing, when shell commands fail.

fab命令默认被安装到Python的目录下,需要创建软链接

 
  1. [root@saltstack ~]# find / -type f -name "fab"

  2. /usr/local/python2.7.10/bin/fab

  3. [root@saltstack ~]# ln -s /usr/local/python2.7.10/bin/fab /usr/bin/fab

fabric 简介 和 各个版本差异比较http://www.mamicode.com/info-detail-2337088.html

入门使用

fabric 的典型使用方式就是,创建一个 Python 文件,该文件包含一到多个函数,然后使用 fab 命令调用这些函数。这些函数在 fabric 中成为 task。

一个示例:

 
  1. from fabric.api import *

  2. from fabric.contrib.console import confirm

  3. from fabric.utils import abort

  4. from fabric.colors import *

  5.  
  6. env.hosts = ['192.168.5.128']

  7. env.port = 22

  8. env.user = 'root'

  9. env.password = 'mysql123'

  10.  
  11.  
  12. def hostname():

  13. run('hostname')

  14.  
  15.  
  16. def ls(path='.'):

  17. run('ls {0}'.format(path))

  18.  
  19.  
  20. def tail(path='/etc/pas', line=10):

  21. run('tail -n {0} {1}'.format(line, path))

  22.  
  23.  
  24. def hello():

  25. with settings(hide('everything'),warn_only=True): # 关闭显示

  26. result = run('anetstat -lntup|grep -w 25')

  27. print(result) # 命令执行的结果

  28. print(result.return_code) # 返回码,0表示正确执行,1表示错误

  29. print(result.failed)

fab 命令执行时,默认引用一个名为 fabfile.py 的文件,我们也可以通过 -f 来进行指定。

这里使用了三个 fabric 的封装:

  1. run:   用于执行远程命令的封装
  2. sudo:以 sudo 权限执行远程命令
  3. env:  保存用户配置的字典 。( 保存了相关的配置,比如登录用户名 env.user,密码 env.password,端口 env.port  等,如果没有指定用户名那么默认使用当前用户,端口使用22 )
 
  1. 1、获取任务列表

  2. pyvip@Vip:~/utils$ fab -f fab_utils.py --list

  3. Available commands:

  4.  
  5. hello

  6. hostname

  7. ls

  8. tail

  9.  
  10. # 2、执行hostname函数

  11. pyvip@Vip:~/utils$ fab -f fab_utils.py hostname

  12. [192.168.5.128] Executing task 'hostname'

  13. [192.168.5.128] run: hostname

  14. [192.168.5.128] out: china

  15. [192.168.5.128] out:

  16.  
  17. Done.

  18. Disconnecting from 192.168.5.128... done.

  19.  
  20. # 3、多个参数的情况

  21. pyvip@Vip:~/utils$ fab -f fab_utils.py ls:/

  22. [192.168.5.128] Executing task 'ls'

  23. [192.168.5.128] run: ls /

  24. [192.168.5.128] out: bin boot data dev etc home lib lib64 lost+found media misc mnt net opt proc root sbin selinux srv sys tmp usr var

  25. [192.168.5.128] out:

  26.  
  27. Done.

  28. Disconnecting from 192.168.5.128... done.

需要注意的是:

  • 一次可以多个 task,按照顺序执行: fab -f fab_util.py hostname ls
  • 给 task 传递参数格式: task:参数。多个参数按照位置进行传递,和Python相同。
    对于关键字的参数可以在命令行中指定。例如:fab ls:path=/home

另一示例

万事从Hello World开始,我们创建一个”fabfile.py”文件,然后写个hello函数:

 
  1. def hello():

  2. print "Hello Fabric!"

现在,让我们在 ”fabfile.py” 的目录下 执行命令:

fab hello

你可以在终端看到”Hello Fabric!”字样。

简单解释下,”fabfile.py”文件中每个函数就是一个任务,任务名即函数名,上例中是”hello”。”fab”命令就是用来执行”fabfile.py”中定义的任务,它必须显式地指定任务名。你可以使用参数”-l”来列出当前”fabfile.py”文件中定义了哪些任务:

fab -l

任务可以带参数,比如我们将hello函数改为:

 
  1. def hello(name, value):

  2. print "Hello Fabric! %s=%s" % (name,value)

此时执行hello任务时,就要传入参数值:

fab hello:name=Year,value=2016

Fabric的脚本建议写在”fabfile.py”文件中,如果你想换文件名,那就要在”fab”命令中用”-f”指定。比如我们将脚本放在”script.py”中,就要执行:

fab -f script.py hello

python3 环境执行

fabric的命令行参数

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

 
  1. # -l:查看task列表

  2.  
  3. # -f:指定fab的入口文件,默认是fabfile.py

  4. # -g:指定网管设备,比如堡垒机环境下,填写堡垒机的IP

  5. # -H:在命令行指定目标服务器,用逗号分隔多个服务器

  6. # -P:以并行方式运行任务,默认为串行

  7. # -R:以角色区分不同的服务

  8. # -t:连接超时的时间,以秒为单位

  9. # -w:命令执行失败时的警告,默认是终止任务

  10. # -- Fabric参数,其他包含fabric脚本的中的参数的快捷操作,比如--user,--port,或者直接跟要执行的Linux命令

如下例子,不写一行代码,获取主机的所有 ip 地址

 
  1. pyvip@Vip:~/utils$ fab -H 192.168.5.128 --port 22 --user='root' --password='mysql123' -- 'ip addr'

  2. [192.168.5.128] Executing task '<remainder>'

  3. [192.168.5.128] run: ip a

  4. [192.168.5.128] out: 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN

  5. [192.168.5.128] out: link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00

  6. [192.168.5.128] out: inet 127.0.0.1/8 scope host lo

  7. [192.168.5.128] out: inet6 ::1/128 scope host

  8. [192.168.5.128] out: valid_lft forever preferred_lft forever

  9. [192.168.5.128] out: 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000

  10. [192.168.5.128] out: link/ether 00:0c:29:96:0a:a0 brd ff:ff:ff:ff:ff:ff

  11. [192.168.5.128] out: inet 192.168.5.128/24 brd 192.168.5.255 scope global eth0

  12. [192.168.5.128] out: inet6 fe80::20c:29ff:fe96:aa0/64 scope link

  13. [192.168.5.128] out: valid_lft forever preferred_lft forever

  14. [192.168.5.128] out: 3: pan0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN

  15. [192.168.5.128] out: link/ether 7a:4d:51:6c:c2:cd brd ff:ff:ff:ff:ff:ff

示例代码:

 
  1. #!/usr/bin/python

  2. # -*- coding:utf-8 -*-

  3.  
  4. from fabric.api import *

  5.  
  6. # 设置服务器登录参数

  7. env.roledefs = {

  8. # 操作一致的放一组,一组执行同一个操作

  9. 'servers1':['root@linux2:22',],

  10. # 第二组

  11. 'servers2':['root@linux3:22',]

  12. }

  13.  
  14. # 本机操作

  15. def localtask():

  16. local('/usr/local/nginx/nginx')

  17.  
  18. # servers1服务器组操作

  19. @roles('servers1')

  20. def task1():

  21. run('/usr/local/tomcat/bin/startup.sh')

  22.  
  23. # servers2 服务器组操作

  24. @roles('servers2')

  25. def task2():

  26. run('/usr/local/tomcat/bin/startup.sh')

  27.  
  28. # 执行任务

  29. def doworks():

  30. execute(localtask)

  31. execute(task1)

  32. execute(task2)

以上代码,就是简单的在本地启动nginx服务器,在linux1和linux2上启动了tomcat服务器,为了接受nginx服务器的代理,这里专门使用分组的方式为了适应机器比较多的集群的需要,另外这里没有设置服务器的密码,一是为了服务器的安全;另外集群间建议设置ssh免密登录,脚本就不用设置密码了,方法doworks执行的就是最终汇总的任务,保存之后,开始执行:

fab -f fabrictest.py doworks

执行之后,脚本会自动的依次执行指定的命令,从控制台可以看到输出,也可以在程序适当位置添加输出,打印一些必要信息

到这里,就看到fabric这个工具的功能确实很强大,更多的编程接口可以查看官网网站的文档:http://www.fabfile.org/

常用的对象和方法介绍

介绍 fabric 中的 env 对象,以及其他的比如执行命令模块,上传文件等。

fabfile 之 env 对象

env是一个全局唯一的字典,保存了Fabric所有的配置,在Fabric的实现中,他是一个_AttributeDict()对象,之所以封装成_AttributeDict()对象,是覆盖了__getattr__和__setattr__,使我们可以使用“对象.属性=值”的方式,操作字典。

 我们可以通过源码的方式,查看env的配置参数,或者使用如下方式查看:

 
  1. import json

  2. from fabric.api import env

  3.  
  4. print(json.dumps(env, indent=3))

  5.  
  6.  
  7. def hell(name='world'):

  8. print('hello %s' % name)

  9.  
  10.  
  11. -----------------------------------------------

  12. 结果

  13.  
  14.  
  15. pyvip@Vip:~/utils$ fab -f fab_utils.py -l

  16. {

  17. "show": null,

  18. "": true,

  19. "sudo_user": null,

  20. "default_port": "22",

  21. "key_filename": null,

  22. "path": "",

  23. "hosts": [

  24. "192.168.5.128"

  25. ],

  26. "host_string": null,

  27. "ok_ret_codes": [

  28. 0

  29. ],

  30. "always_use_pty": true,

  31. "fabfile": "fab_utils.py",

  32. "echo_stdin": true,

  33. "again_prompt": "Sorry, try again.",

  34. "command": null,

  35. "forward_agent": false,

  36. "command_prefixes": [],

  37. "cwd": "",

  38. "connection_attempts": 1,

  39. "linewise": false,

  40. "gateway": null,

  41. "use_exceptions_for": {

  42. "network": false

  43. ……

env 对象的作用是定义 fabfile 的全局属性设定。下面对各属性进行说明:

  • env.host : 定义目标主机,如:env.host=['192.168.56.1', '192.168.56.2']
  • env.exclude_hosts:  排除指定主机,如env.exclude_hosts=['192.168.1.21']
  • env.user : 定义用户名,如:env.user="root"
  • env.port : 定义目标主机端口,默认为22,如:env.port="22"
  • env.key_filename:私钥文件的位置
  • env.password : 定义密码,如:env.password="passwd"
  • env.passwords :  定义多个密码,不同的主机对应不同的密码,如:env.passwords={'[email protected]:22':'passwd', '[email protected]:22':'python'}
  • 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等

针对不同主机不同密码的情况,可以使用如下的方式:

 
  1. env.hosts = [

  2. '[email protected]:22',

  3. '[email protected]:22',

  4. '[email protected]:22'

  5. ]

  6. env.passwords = {

  7. '[email protected]:22':'123456201',

  8. '[email protected]:22':'123456202',

  9. '[email protected]:22':'123456203'

使用示例(fabric_3.py):

 
  1. from fabric.api import run,cd,env,hosts

  2. env.hosts=['192.168.20.140:22','172.16.1.150:22'] # env.hosts=['user@ip:port',] ssh要用到的参数格式

  3. env.password='strong'

  4.  
  5. def host_type():

  6. with cd('/tmp/'):

  7. run('du -ksh *')

执行命令: [root@saltstack fabric]# fab -f fabric_3.py host_type

多台服务器混合,需要在不同服务器进行不同操作时(fabric_4.py)

 
  1. #!/usr/bin/env python

  2. # coding:utf-8

  3.  
  4. from fabric.api import env,roles,run,execute

  5.  
  6. env.roledefs = {

  7. 'server1': ['[email protected]:22',],

  8. 'server2': ['[email protected]:22', ]

  9. }

  10.  
  11. env.password = 'strong'

  12. @roles('server1')

  13. def task1():

  14. run('ls /home/ -l | wc -l')

  15.  
  16. @roles('server2')

  17. def task2():

  18. run('du -sh /home')

  19.  
  20. def test(): # 调节主机组和主机组执行操作的顺序

  21. execute(task2)

  22. execute(task1)

执行命令:[root@saltstack fabric]# fab -f fabric_4.py test

密码管理,看文档
1. host,user,port,password 配置列表,所有的都写在一个文件或者直接搞到脚本里,当然这个更........

代码如下:

 
  1. env.hosts = [

  2.     'host1',

  3.     'host2'

  4. ]

  5. env.passwords = { 

  6.     'host1': "pwdofhost1",

  7.     'host2': "pwdofhost2",

  8. }

或者

 
  1. env.roledefs = {

  2.     'testserver': ['host1', 'host2'],

  3.     'realserver': ['host3', ]

  4. }

  5. env.passwords = {

  6.     'host1': "pwdofhost1",

  7.     'host2': "pwdofhost2",

  8.     'host3': "pwdofhost3", 

  9. }

Fabric 提供的命令(SSH功能函数)

Fabric的核心API主要有7类:带颜色的输出类(color output)、上下文管理类(context managers)、装饰器类(decorators)、网络类(network)、操作类(operations)、任务类(tasks)、工具类(utils)。

Fabric提供了一组操作简单但功能强大的fabric.api命令集,简单地调用这些API就能完成大部分应用场景的需求。

Fabric.api 是Fabric中最常用也是最核心的模块。可以使用此模块来实现与远程服务器的交互。简单的使用这些API就可以完成大部分应用场景的需求。Fabric支持的常用命令及说明如下:

  • local:                          在本地执行命令。local(‘username -r’)
  • run:                            在远程执行命令。run(‘username -r’)
  • sudo(cmd):                以超级用户权限执行远程命令。 sudo("mkdir /root/xx")
  • get(remote, local):     从远程机器上下载文件到本地
  • put(local, remote):     从本地上传文件到远程机器上
  • prompt(提示字符串, default, validate): 提示输入并返回用户输入值。即获取用户输入(类似input)    prompt(‘input path’)
  • confirm:   让用户确认是否继续    confirm(‘continue?’)
  • reboot:       重启服务器
  • cd(path):    设置远程机器的当前工作目录 。cd(‘/usr’)
  • lcd(path):   设置本地工作目录。                  lcd(‘/usr’)
  • path:          添加远程机的PATH路径
  • settings:     设置Fabric环境变量参数
  • shell_env:  设置Shell环境变量
  • prefix:        设置命令执行前缀
  • env:           定义全局信息,如主机、密码等    env.hosts=’localhost’

示例代码 1:

 
  1. from fabric.api import * #导入fabric.api模块

  2. env.hosts= ['192.168.122.101','192.168.122.102','192.168.122.103'] #指定远端服务器的ip地址。如果有dns解析的也可以写主机名。

  3. env.password='indionce' #指定远端主机的密码,如果各个密码不相同可以使用一个字典指定,例如:env.password={“[email protected]”:"indionce"}

  4. def local_uname(): #定义一个本地任务的函数

  5. local('uname -r')

  6. def remote_uname(): #定义一个远程任务的函数

  7. run('uname -r')

  8. def uname(): #定义一个函数,将本地与远端组合起来使用

  9. local_uname()

  10. remote_uname()

尽管我只保留了前两台主机的返回值,但是也可以从中发现。我有多少台主机,脚本便执行了多少次本地的uname -r。在实际应用中,有很多类似内核信息的本地命令,我只需要执行一次。甚至多次执行会出现错误,这时我就需要使用@runs_once来对函数进行修饰,具体使用也非常简单,如下:

 
  1. @runs_once #指定下一行的函数在运行时,只运行一次。

  2. def local_uname():

  3. local('uname -r')

新脚本执行之后就会发现本地的内核信息只输出了一次。

示例代码 2:

查看远程服务器的文件夹列表

 
  1. from fabric.api import *

  2.  
  3. @runs_once #一定要指定这一条,否则会让你输入多次路径

  4. def input():

  5. return prompt("input path:") # prompt函数,让用户输入自己想要的路径,将输入的值返回到函数。

  6. def ls_path(dirname): #在定义函数的时候指定形参。

  7. run("ls -l "+dirname)

  8. def go():

  9. ls_path(input()) #使用input返回的值,用于ls_path()的参数

执行这个脚本:[root@name ~]# fab go 

run()

run():在远程服务器上执行 Linux命令,还有一个重要的参数 pty,如果我们执行命令以后需要有一个常驻的服务进程,那么就需要设置 pty=False,避免因为 Fabric 退出导致进程的退出。

run('service mysqld start',pty=False)

                关于 " fabric nohup " 问题,可以百度 " fabric nohup "。

                这里给出两个解决方案的文章地址:

                        Fabric 与 nohup 的问题:https://segmentfault.com/a/1190000000612750

                        Fabric With Nohup 执行方式:https://blog.csdn.net/orangleliu/article/details/30223757

PS:上面命令执行完毕会返回输出的信息,我们可以定义变量接受,同时这个返回信息有一个方法return_code,当返回的是正确执行的结果时code为0,否则不为0

 
  1. def hello():

  2. with settings(hide('everything'), warn_only=True): # 关闭显示

  3. result = run('anetstat -lntup|grep -w 25')

  4. print(result) # 命令执行的结果

  5. print(result.return_code) # 返回码,0表示正确执行,1表示错误

其实 Fabric 真正强大之处不是在执行本地命令,而是可以方便的执行远程机器上的 Shell 命令。它通过 SSH 实现。你需要的是在脚本中配置远程机器地址及登录信息:

在 远程机器 执行命令 示例方法 1:

 
  1. from fabric.api import *

  2.  
  3. env.passwords = {

  4. "[email protected]:22":"password"

  5. }

  6.  
  7. @hosts("[email protected]:22")

  8. def hello():

  9. run("ls -l ~")

我们可以通过设置 env.passwords 来避免在运行过程中输密码,注意ip后面需要加端口号,示例中的22是ssh的端口号。

在 远程机器 执行命令 示例方法 2:

 
  1. from fabric.api import run, env

  2.  
  3. env.hosts = ['example1.com', 'example2.com']

  4. env.user = 'bjhee'

  5. env.password = '111111'

  6.  
  7. def hello():

  8. run('ls -l /home/bjhee/')

run() 方法可以用来执行远程Shell命令。上面的任务会分别到两台服务器”example1.com”和”example2.com”上执行”ls -l /home/bjhee/”命令。这里假设两台服务器的用户名都是”bjhee”,密码都是6个1。你也可以把用户直接写在hosts里,比如:

env.hosts = ['[email protected]', '[email protected]']

如果你的”env.hosts”里没有配置某个服务器,但是你又想在这个服务器上执行任务,你可以在命令行中通过”-H”指定远程服务器地址,多个服务器地址用逗号分隔:

fab -H [email protected],[email protected] hello

另外,多台机器的任务是串行执行的,关于并行任务的执行我们在之后会介绍。

如果对于不同的服务器,我们想执行不同的任务,上面的方法似乎做不到,那怎么办?我们要对服务器定义角色:

 
  1. from fabric.api import env, roles, run, execute, cd

  2.  
  3. env.roledefs = {

  4. 'staging': ['[email protected]','[email protected]'],

  5. 'build': ['[email protected]']

  6. }

  7.  
  8. env.passwords = {

  9. 'staging': '11111',

  10. 'build': '123456'

  11. }

  12.  
  13. @roles('build')

  14. def build():

  15. with cd('/home/build/myapp/'):

  16. run('git pull')

  17. run('python setup.py')

  18.  
  19. @roles('staging')

  20. def deploy():

  21. run('tar xfz /tmp/myapp.tar.gz')

  22. run('cp /tmp/myapp /home/bjhee/www/')

  23.  
  24. def task():

  25. execute(build)

  26. execute(deploy)

现在让我们执行:$ fab task

这时 Fabric 会先在一台 build 服务器上执行 build 任务,然后在两台 staging 服务器上分别执行 deploy 任务。”@roles” 装饰器指定了它所装饰的任务会被哪个角色的服务器执行。

如果某一任务上没有指定某个角色,但是你又想让这个角色的服务器也能运行该任务,你可以通过 ”-R” 来指定角色名,多个角色用逗号分隔:$ fab -R build deploy

这样 ”build” 和 ”staging” 角色的服务器都会运行 ”deploy” 任务了。注:”staging” 是装饰器默认的,因此不用通过 ”-R” 指定。

此外,上面的例子中,服务器的登录密码都是明文写在脚本里的。这样做不安全,推荐的方式是设置 SSH 自动登录,具体方法大家可以去网上搜搜。

跨网关的使用

实际使用中服务器的网关一帮的设有防火墙,我们无法直接ssh管理服务器。Fabric也提供给我们一种夸网关的使用方式。只需要在配置文件中定义好网关的ip地址,即需要设置 env.gateway。具体如下:

 
  1. from fabric.api import *

  2. from fabric.contrib.console import confirm

  3. env.user = "root"

  4. env.gateway = '10.0.0.1' #定义网关的地址

  5. env.hosts = ["10.0.0.2","10.0.0.3"]

  6. env.passwords = {

  7. '[email protected]:22':'redhat', #需要定义网关的密码

  8. '[email protected]:22':'redhat',

  9. '[email protected]:22':'redhat'

  10. }

在内网机器执行命令 示例代码 2:

 
  1. from fabric.api import *

  2.  
  3. env.gateway = "[email protected]:22"

  4. env.passwords = {

  5. "[email protected]:22":"password1"

  6. "[email protected]:22":"password2"

  7. }

  8.  
  9. @hosts("[email protected]:22")

  10. def hello():

  11. run("ls -l ~")

密码管理

1)Fabric既支持ssh公钥认证也支持管理密码的机制

2)Fabric的密码管理机制提供了两层密码。如果你的server有相同的密码,可以在env.password中设置默认的密码;如果server密码不同,还可以在env.passwords中设置(host,password)对,为每个server设置单独的ssh密码。

网关模式文件上传与执行

本例通过定义env.gateway网关模式,即俗称的中转、堡垒机环境。通过网关对其他主机进行文件上传和执行。

 
  1. #!/usr/bin/env python

  2. # -*- encoding: utf-8 -*-

  3.  
  4. from fabric.api import *

  5. from fabric.context_managers import *

  6. from fabric.contrib.console import confirm

  7.  
  8. env.user = 'root'

  9. env.gateway = '192.168.1.23' #定义堡垒机IP,作为文件上传、执行的中转设置

  10. env.hosts = ['192.168.1.21','192.168.1.22']

  11. env.passwords = {

  12. '[email protected]:22':'123456',

  13. '[email protected]:22':'abcdef',

  14. '[email protected]:22':'123abc', #堡垒机账号信息

  15. }

  16.  
  17. lpackpath = '/home/install/lnmp.tar.gz' #本地安装包路径

  18. rpackpath = '/tmp/install' #远程安装包路径

  19.  
  20.  
  21. @task

  22. def put_task(): #上传文件

  23. run('mkdir -p /tmp/install')

  24. #默认情况下,当命令执行失败时,Fabric会停止执行后续命令。有时,我们允许忽略失败的命令继续执行,比如run(‘rm /tmp/abc')在文件不存在的时候有可能失败,这时可以用with settings(warn_only=True):执行命令,这样Fabric只会打出警告信息而不会中断执行。

  25. with settings(warn_only=True):

  26. result = put(lpackpath,rpackpath) #上传

  27. if result.failed and not confirm('put file failed,Continue[Y/N]?'):

  28. abort('Aborting file put task!')

  29.  
  30. @task

  31. def run_task(): #安装

  32. with cd('/tmp/install'):

  33. run('tar -zxvf lnmp.tar.gz')

  34. with cd('lnmp/'): #使用with继承/tmp/install目录位置状态

  35. run('./centos.sh')

  36.  
  37.  
  38. @task

  39. def go(): #上传、安装组合命令

  40. put_task()

  41. run_task()

  42.  
  43. simple3.py

  44.  
  45. simple3.py

执行命令:

 
  1. #上传文件

  2. fab simple3.py put_task

  3. #执行文件

  4. fab simple3.py run_task

  5. #上传并执行

  6. fab simple3.py go

sudo()

sudo():功能与 run() 方法类似,只是是使用管理员权限在远程服务器上执行shell命令,区别是它相当于在 Shell 命令前加上了”sudo”,所以拥有超级用户的权限。使用此功能前,你需要将你的用户设为sudoer,而且无需输密码。具体操作可参见我的这篇文章。还有一个重要的参数 pty,如果我们执行命令以后需要有一个常驻的服务进程,那么就需要设置 pty=False,避免因为 Fabric 退出导致进程的退出。

 
  1. from fabric.api import env, sudo

  2.  
  3. env.hosts = ['[email protected]', '[email protected]']

  4. env.password = '111111'

  5.  
  6. def hello():

  7. sudo('mkdir /var/www/myapp')

local()

local():用来执行本地 Shell 命令,返回要执行的命令,local 是对 Python 的 Subprocess 模块的封装,更负载的功能可以直接使用 Subprocess 模块,包含 capture 参数,默认为 False,表示 subprocess 输出的信息进行显示,如果不想显示,那么指定capture=True 即可

 
  1. ef test():

  2. result = local('make test',capture=True)

  3. print(result)

  4. print(result.failed)

  5. print(result.succeeded)

  6.  
  7. # 返回执行的命令

  8. # 如果执行失败那么 result.failed 为True

  9. # 如果执行成功那么 result.succeeded 为True

列出本地  /home/bjhee  目录下的所有文件及目录:

 
  1. from fabric.api import local

  2.  
  3. def hello():

  4. local('ls -l /home/bjhee/')

使用 capture 参数 用来 捕获 标准输出,比如:

 
  1. def hello():

  2. output = local('echo Hello', capture=True)

这样,Hello字样不会输出到屏幕上,而是保存在变量output里。”capture”参数的默认值是False。

get()

get():从远程服务器上获取文件,通过remote_path参数声明从何处下载,通过local_path表示下载到何处。remote_path支持通配符。

get(remote_path='/etc/passwd',local_path='/tmp/passwd')

它的工作原理是基于scp命令,使用的方法如下:

 
  1. from fabric.api import env, get

  2.  
  3. env.hosts = ['[email protected]',]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. get('/var/log/myapp.log', 'myapp-0301.log')

上述任务将远程机上”/var/log/myapp.log”文件下载到本地当前目录,并命名为”myapp-0301.log”。

put()

put():将本地的文件上传到远程服务器,参数与get相似,此外,还可以通过mode参数执行远程文件的权限配置。

put(remote_path='/etc/passwd',local_path='/tmp/passwd')

同 get一样,put 方法也是基于scp命令,使用的方法如下:

 
  1. from fabric.api import env, put

  2.  
  3. env.hosts = ['[email protected]', '[email protected]']

  4. env.password = '111111'

  5.  
  6. def hello():

  7. put('/tmp/myapp-0301.tar.gz', '/var/www/myapp.tar.gz')

上述任务将本地”/tmp/myapp-0301.tar.gz”文件分别上传到两台远程机的”/var/www/”目录下,并命名为”myapp.tar.gz”。如果远程机上的目录需要超级用户权限才能放文件,可以在”put()”方法里加上”use_sudo”参数:

put('/tmp/myapp-0301.tar.gz', '/var/www/myapp.tar.gz', use_sudo=True)

上传文件并执行 示例代码:

 
  1. from fabric.api import *

  2.  
  3. env.user = 'mysql'

  4. env.hosts = ['192.168.56.1', '192.168.56.2']

  5. #env.password = '1qaz@WSX'

  6. env.passwords = {

  7. '[email protected]:22':'1qaz@WSX',

  8. '[email protected]:22':'1qaz@WSX',

  9. }

  10.  
  11. @task

  12. @runs_once

  13. def tar_task():

  14. with lcd('/home/mysql/yanjun_wang'):

  15. local('tar zcvf hello.tar.gz hello_world.py')

  16.  
  17. @task

  18. def put_task():

  19. run('mkdir -p /home/mysql/yanjun_wang')

  20. with cd('/home/mysql/yanjun_wang'):

  21. put('/home/mysql/yanjun_wang/hello.tar.gz', '/home/mysql/yanjun_wang/hello.tar.gz')

  22.  
  23. @task

  24. def check_task():

  25. lmd5 = local('md5sum /home/mysql/yanjun_wang/hello.tar.gz', capture=True).split(' ')[0]

  26. rmd5 = run('md5sum /home/mysql/yanjun_wang/hello.tar.gz').split(' ')[0]

  27. if lmd5 == rmd5:

  28. print('OK ...')

  29. else:

  30. print('ERROR ...')

  31.  
  32. @task

  33. def run_task():

  34. with cd('/home/mysql/yanjun_wang'):

  35. run('tar zxvf hello.tar.gz')

  36. run('python hello_world.py')

  37.  
  38. @task

  39. def execute():

  40. print('start ...')

  41. tar_task()

  42. put_task()

  43. check_task()

  44. run_task()

  45. print('end ...')

文件打包上传校验 示例代码:

 
  1. #!/usr/bin/env python

  2. from fabric.api import *

  3. from fabric.colors import *

  4.  
  5. env.hosts=['192.168.56.30']

  6. env.user='root'

  7. env.passwords={'[email protected]:22':'rooter'}

  8.  
  9. @runs_once

  10. @task

  11. def tarfile():

  12. print yellow('tar file ...')

  13. #使用with lcd命令,否则需要写全路径,直接lcd没用

  14. with lcd('/var/log'):

  15. local('tar czf messages.tar.gz messages')

  16.  
  17. @task

  18. def putfile():

  19. print blue('put file ...')

  20. run('mkdir -p /tmp/log')

  21. with cd('/tmp/log'):

  22. #warn_only当出现异常的时候继续执行

  23. with settings(warn_only=True):

  24. result=put('/var/log/messages.tar.gz','/tmp/log')

  25. if result.failed and not confirm('put file filed,Continue[Y/N]?'):

  26. abort('Aborting file put task!')

  27.  
  28. @task

  29. def checkfile():

  30. print red('check file ...')

  31. with settings(warn_only=True):

  32. #本地local命令需要配置capture=True才能获取返回值

  33. lmd5=local('md5sum /var/log/messages.tar.gz',capture=True).split(' ')[0]

  34. rmd5=run('md5sum /tmp/log/messages.tar.gz').split(' ')[0]

  35. if lmd5==rmd5:

  36. print 'ok'

  37. else:

  38. print 'error'

  39.  
  40. @task

  41. def go():

  42. tarfile()

  43. putfile()

  44. checkfile()

  45.  
  46. simple3.py

下面是运行结果,有颜色的区别:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

[192.168.56.30] Executing task 'go'

tar file ...

[localhost] local: tar czf messages.tar.gz messages

put file ...

[192.168.56.30] run: mkdir -/tmp/log

[192.168.56.30] put: /var/log/messages.tar.gz -/tmp/log/messages.tar.gz

check file ...

[localhost] local: md5sum /var/log/messages.tar.gz

[192.168.56.30] run: md5sum /tmp/log/messages.tar.gz

[192.168.56.30] out: 958b813fd7bdaa61cc206aa1012d8129  /tmp/log/messages.tar.gz

[192.168.56.30] out:

  

ok

  

Done.

Disconnecting from 192.168.56.30... done

reboot()

reboot():重启远程服务器,可以通过wait参数设置等待几秒钟重启

reboot(wait=30)

有时候安装好环境后,需要重启服务器,这时就要用到”reboot()”方法,你可以用”wait”参数来控制其等待多少秒后重启,没有此参数则代表立即重启:

 
  1. from fabric.api import env, reboot

  2.  
  3. env.hosts = ['[email protected]',]

  4. env.password = '111111'

  5.  
  6. def restart():

  7. reboot(wait=60)

上面的restart任务将在一分钟后重启服务器。

propmt()

propmt():用以在 Fabric 执行任务的过程中与管理员进行交互,类似于python 的 input

 
  1. key = prompt('Please specify process nice level:',key='nice',validate=int)

  2. # 会返回采集到的key

该方法也类似于 Shell 中的 ”read” 命令,它会在终端显示一段文字来提示用户输入,并将用户的输入保存在变量里:

 
  1. from fabric.api import env, get, prompt

  2.  
  3. env.hosts = ['[email protected]',]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. filename = prompt('Please input file name: ')

  8. get('/var/log/myapp.log', '%s.log' % filename)

现在下载后的文件名将由用户的输入来决定。我们还可以对用户输入给出默认值及类型检查:

port = prompt('Please input port number: ', default=8080, validate=int)

执行任务后,终端会显示:Please input port number: [8080]

如果你直接按回车,则port变量即为默认值8080;如果你输入字符串,终端会提醒你类型验证失败,让你重新输入,直到正确为止。

示例代码(动态获取远程目录列表):

本例调用@task修饰符标志入口函数go()对外部可见,配合@runs_once修饰符接收用户输入,最后调用worktask()函数实现远程命令执行。

 
  1. #!/usr/bin/env python

  2. # -*- encoding: utf-8 -*-

  3.  
  4. from fabric.api import *

  5.  
  6. env.user = 'root'

  7. env.hosts = ['192.168.1.22']

  8. env.password = '123456'

  9.  
  10. @runs_once #主机遍历过程中,只有第一台触发此函数

  11. def input_raw():

  12. return prompt('please input directoryname:',default='/root')

  13.  
  14. def worktask(dirname):

  15. run('ls -l'+dirname)

  16.  
  17. @task #限定只有go函数对fab命令可见,其他没有使用@task标记的函数fab命令不可用

  18. def go():

  19. getdirname = input_raw()

  20. worktask(getdirname)

  21.  
  22. simple2.py

执行:fab -f simple2.py go

对于上面的结果做了一些测试发现:

1.设置了默认值,不输入就是以默认值为准,如果不设置默认值,那么dirname就是空的,ls -l的就是你登录用户的家目录,例如是root就是/root

2.对于写在go函数下的内容,有多少主机就会循环多少次,他是以主机为循环的.

3.这个脚本是对于所有的主机列出同一个目录,对于不同的主机让选择不同的目录,可以简单的修改为:

 
  1. def worktask(dirname):

  2. run('ls -l '+dirname)

  3.  
  4. @task

  5. def go():

  6. getdirname=raw_input("please input directory:")

  7. worktask(getdirname)

如果你正在寻找一个用户来确认操作,请使用confrim方法。
    if fabric.contrib.console.confirm("You tests failed do you want to continue?"):
     #continue processing

如果你正在寻找从用户那里获取输入的方法,请使用提示方法。
    password = fabric.operations.prompt("What is your password?")

在windows服务器执行命令

首先windows机器需要安装ssh服务,注意ssh服务所用的账户需要设置能够运行exec的权限,否则无法启动windwos程序。
其次由于fabric默认使用bash,因此需要设置变量 env.shell="cmd /c",否则会报错。

上下文管理器

env 中存储的是全局配置,有时候我们并不希望修改全局配置参数,只希望临时修改部分配置,例如:修改当前工作目录,修改日志输出级别等。在 fabric 中我们可以通过上下文管理器临时修改参数配置,而不会影响全局配置。当程序进入上下文管理器的作用域时,临时修改就会起作用;当程序离开上下文管理器时,临时修改就会消失。

Fabric 的上下文管理器是一系列与 Python 的 ”with” 语句配合使用的方法,它可以在 ”with” 语句块内设置当前工作环境的上下文。让我们介绍几个常用的:

cd():切换远程目录

 
  1. def change(dir='/tmp'):

  2. with cd(dir):

  3. run('pwd') # /tmp

  4. run('pwd') # /root

“cd()”方法在之前的范例中出现过,”with cd()”语句块可以用来设置远程机的工作目录:

 
  1. from fabric.api import env, cd, put

  2.  
  3. env.hosts = ['[email protected]', ]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. with cd('/var/www/'):

  8. put('/tmp/myapp-0301.tar.gz', 'myapp.tar.gz')

上例中的文件会上传到远程机的”/var/www/”目录下。出了”with cd()”语句块后,工作目录就回到初始的状态,也就是”bjhee”用户的根目录。

lcd: 设置本地工作目录

“lcd()”就是”local cd”的意思,用法同”cd()”一样,区别是它设置的是本地的工作目录:

 
  1. from fabric.api import env, cd, lcd, put

  2.  
  3. env.hosts = ['[email protected]', ]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. with cd('/var/www/'):

  8. with lcd('/tmp/'):

  9. put('myapp-0301.tar.gz', 'myapp.tar.gz')

这个例子的执行效果跟上个例子一样。

path():配置远程服务器PATH环境变量,只对当前会话有效,不会影响远程服务器的其他操作,path的修改支持多种模式

  • append:默认行为,将给定的路径添加到PATH后面。
  • prepend:将给定的路径添加到PATH的前面。
  • replace:替换当前环境的PATH变量。
 
  1. def addpath():

  2. with path('/tmp','prepend'):

  3. run("echo $PATH")

  4. run("echo $PATH")

添加远程机的 PATH 路径

 
  1. from fabric.api import env, run, path

  2.  
  3. env.hosts = ['[email protected]', ]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. with path('/home/bjhee/tmp'):

  8. run('echo $PATH')

  9. run('echo $PATH')

假设我们的PATH环境变量默认是”/sbin:/bin”,在上述”with path()”语句块内PATH变量将变为”/sbin:/bin:/home/bjhee/tmp”。出了with语句块后,PATH又回到原来的值。

prefix:设置命令执行前缀。

        prefix() 前缀,它接受一个命令作为参数,表示在其内部执行的代码块,都要先执行prefix的命令参数。

 
  1. from fabric.api import env, run, local, prefix

  2.  
  3. env.hosts = ['[email protected]', ]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. with prefix('echo Hi'):

  8. run('pwd')

  9. local('pwd')

示例代码 2 :

 
  1. def testprefix():

  2. with cd('/tmp'):

  3. with prefix('echo 123'):

  4. run('echo 456')

  5. run('echo 789')

  6.  
  7. # 转换为Linux命令为:

  8. cd /tmp && echo '123' && echo '456'

  9. cd /tmp && echo '123' && echo '789' 

在上述”with prefix()”语句块内,所有的”run()”或”local()”方法的执行都会加上”echo Hi && “前缀,也就是效果等同于:

 
  1. run('echo Hi && pwd')

  2. local('echo Hi && pwd')

配合后面的错误处理,它可以确保在”prefix()”方法上的命令执行成功后才会执行语句块内的命令。

shell_env():设置 shell 脚本的环境变量。可以用来临时设置远程和本地机上Shell的环境变量。

 
  1. def setenv():

  2. with shell_env(HTTP_PROXY='1.1.1.1'):

  3. run('echo $HTTP_PROXY')

  4. run('echo $HTTP_PROXY')

  5.  
  6. # 等同于shell中的export

  7. export HTTP_PROXY='1.1.1.1'

示例:

 
  1. from fabric.api import env, run, local, shell_env

  2.  
  3. env.hosts = ['[email protected]', ]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. with shell_env(JAVA_HOME='/opt/java'):

  8. run('echo $JAVA_HOME')

  9. local('echo $JAVA_HOME')

settings():通用配置,设置Fabric环境变量参数,用于临时覆盖env变量。

 
  1. def who():

  2. with settings(user='dev'): # 临时修改用户名为dev

  3. run('who')

  4. run('who')

Fabric 环境变量即是我们例子中一直出现的 ”fabric.api.env ”,它支持的参数可以从官方文档中查到。

 
  1. from fabric.api import env, run, settings

  2.  
  3. env.hosts = ['[email protected]', ]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. with settings(warn_only=True):

  8. run('echo $USER')

我们将环境参数”warn_only”暂时设为True,这样遇到错误时任务不会退出。

remote_tunnel():通过SSH的端口转发建立的链接

 
  1. with remote_tunnel(3306):

  2. run('mysql -uroot -p password')

hide():用于隐藏指定类型的输出信息,hide定义的可选类型有7种

  • status:状态信息,如服务器断开链接,用户使用ctrl+C等,如果Fabric顺利执行,不会有状态信息
  • aborts:终止信息,一般将fabric当作库使用的时候需要关闭
  • warnings:警告信息,如grep的字符串不在文件中
  • running:fabric运行过程中的数据
  • stdout:执行shell命令的标准输出
  • stderr:执行shell命令的错误输出
  • user:用户输出,类似于Python中的print函数

为了方便使用,fabric对以上其中类型做了进一步的封装

  • output:包含stdout,stderr
  • everything:包含stdout,stderr,warnings,running,user
  • commands:包含stdout,running

show():与hide相反,表示显示指定类型的输出

 
  1. def hello():

  2. with settings(show('everything'),warn_only=True): # 显示所有

  3. result = run('netstat -lntup|grep')

  4. print('1='+result) # 命令执行的结果

  5. print('2='+str(result.return_code)) # 返回码,0表示正确执行,1表示错误

  6. print('3='+str(result.failed))

结果:

 
  1. pyvip@Vip:~/utils$ fab -f fab_utils.py hello

  2. [192.168.5.128] Executing task 'hello'

  3. [192.168.5.128] run: netstat -lntup|grep

  4. [192.168.5.128] out: 用法: grep [选项]... PATTERN [FILE]...

  5. [192.168.5.128] out: 试用‘grep --help’来获得更多信息。

  6. [192.168.5.128] out:

  7.  
  8.  
  9. Warning: run() received nonzero return code 2 while executing 'netstat -lntup|grep'!

  10.  
  11. NoneType

  12.  
  13.  
  14. 1=用法: grep [选项]... PATTERN [FILE]...

  15. 试用‘grep --help’来获得更多信息。

  16. 2=2

  17. 3=True

  18.  
  19. Done.

quiet():隐藏全部输出,仅在执行错误的时候发出告警信息,功能等同于 with settings(hide('everything'),warn_only=True) .

 
  1. # 比如创建目录的时候,如果目录存在,默认情况下Fabric会报错退出,我们是允许这种错误的,

  2. # 所以针对这种错误,我们进行如下设置,使 fabric 只打出告警信息而不会中断执行。

  3. with settings(warn_only=True)

错误及异常

在执行任务中,难免出现命令执行失败的情况。而在日常使用中,肯定不会像我们测试时只执行一两条命令,一般都是一系列命令来共同完成一件事。如果其中一条命令执行失败,便会影响后续的命令。这个时候我们要让脚本停下来,以免出现更大的错误。 Fabric 会检查被调用程序的返回值,如果这些程序没有干净地退出,Fabric 会终止操作。fab 程序在执行脚本出错的时候会自动终止,不再继续往下执行。

默认,一组命令,上一个命令执行失败后,不会接着往下执行,失败后也可以进行不一样的处理,详解文档

# 默认情况
[root@saltstack fabric]# cat fabric_6.py

 
  1. #!/usr/bin/env python

  2. # coding:utf-8

  3.  
  4. #from fabric.api import run

  5. from fabric.api import local

  6.  
  7. def host_type():

  8. local('uname -s')

  9. local('tt')

  10. local('hostname')

  11.  
  12. [root@saltstack fabric]# fab -H localhost -f fabric_6.py host_type

  13. [localhost] Executing task 'host_type'

  14. [localhost] local: uname -s

  15. Linux

  16. [localhost] local: tt

  17. /bin/sh: tt: command not found

  18.  
  19. Fatal error: local() encountered an error (return code 127) while executing 'tt'

  20.  
  21. Aborting.

  22. # 注:由于tt执行报错,后面的hostname命令没有被执行

[root@saltstack fabric]# cat fabric_7.py

 
  1. #!/usr/bin/env python

  2. # coding:utf-8

  3.  
  4. from __future__ import with_statement

  5. from fabric.api import local, settings, abort

  6. from fabric.colors import *

  7. from fabric.contrib.console import confirm

  8.  
  9. def host_type():

  10. local('uname -s')

  11. with settings(warn_only=True):

  12. result = local('tt', capture=True)

  13. if result.failed and not confirm(red("tt cmd failed. Continue anyway?")):

  14. abort("Aborting at user request.")

  15. local('hostname')

  16. [root@saltstack fabric]# fab -H localhost -f fabric_7.py host_type

  17. [localhost] Executing task 'host_type'

  18. [localhost] local: uname -s

  19. Linux

  20. [localhost] local: tt

  21.  
  22. Warning: local() encountered an error (return code 127) while executing 'tt'

  23.  
  24. tt cmd failed. Continue anyway? [Y/n] y # 判断上一步执行有无异常,异常给予提示,确认是否继续

  25. [localhost] local: hostname

  26. saltstack

  27.  
  28. Done.

如果我们想要更加灵活,给用户另一种选择,一个名为warn_only的设置就排上用场了。可以把退出换为警告,以提供更灵活的错误处理。具体如下:

 
  1. from fabric.api import *

  2. from fabric.contrib.console import * #这个模块中包含confirm

  3. def backup():

  4. with settings(warn_only=True): #with命令表示执行这句后,执行下面的命令。使用settings命令来设置警告模式

  5. state=local('mkdir /root/zz') #创建一个文件夹

  6. if state.failed and not confirm("/root/zz is already exist,continue?"): #使用failed来判断state这条命令是否失败,失败了为真。confirm向用户确认是否继续,继续为真。如果命令失败了,并且用户希望停止,便通过if判断。

  7. abort("退出任务") #abort是退出任务,有些类似python的exit。退出并且时返回给用户一串字符串

  8. local('tar cavf /root/zz/etc.tar.gz /etc') #将etc的文件备份到/root/zz文件夹中

运行该文件得到下列结果,出现错误时向用户提示错误,用户可以视情况自行选择是否继续。

 
  1. [root@Fabric ~]# fab mkdir

  2. [192.168.122.101] Executing task 'mkdir'

  3. [localhost] local: mkdir /root/zz

  4. mkdir: 无法创建目录"/root/zz": 文件已存在

  5.  
  6. Warning: local() encountered an error (return code 1) while executing 'mkdir /root/zz'

  7.  
  8. /root/zz is already exist,continue? [Y/n] a

  9. I didn't understand you. Please specify '(y)es' or '(n)o'.

  10. /root/zz is already exist,continue? [Y/n]

默认情况下,Fabric在任务遇到错误时就会退出,如果我们希望捕获这个错误而不是退出任务的话,就要开启”warn_only”参数。在上面介绍”settings()”上下文管理器时,我们已经看到了临时开启”warn_only”的方法了,如果要全局开启,有两个办法:

1. 在执行”fab”命令时加上”-w”参数: $ fab -w hello
2. 设置 ”env.warn_only” 环境参数为 True

 
  1. from fabric.api import env

  2.  
  3. env.warn_only = True

现在遇到错误时,控制台会打出一个警告信息,然后继续执行后续任务。那我们怎么捕获错误并处理呢?像”run()”, “local()”, “sudo()”, “get()”, “put()”等SSH功能函数都有返回值。当返回值的”succeeded”属性为True时,说明执行成功,反之就是失败。你也可以检查返回值的”failed”属性,为True时就表示执行失败,有错误发生。在开启”warn_only”后,你可以通过”failed”属性检查捕获错误,并执行相应的操作。

 
  1. from fabric.api import env, cd, put

  2.  
  3. env.hosts = ['[email protected]', ]

  4. env.password = '111111'

  5.  
  6. def hello():

  7. with cd('/var/www/'):

  8. upload = put('/tmp/myapp-0301.tar.gz', 'myapp.tar.gz')

  9. if upload.failed:

  10. sudo('rm myapp.tar.gz')

  11. put('/tmp/myapp-0301.tar.gz', 'myapp.tar.gz', use_sudo=True)

装饰器

Fabric提供的命令一般都是执行某一个具体的操作,提供的上下文管理器一般都是用于临时修改配置参数,而fabric提供的装饰器,既不是执行具体的操作,也不是修改参数,而是控制如何执行这些操作,在那些服务器上执行这些操作,fabric的装饰器与人物执行紧密相关。下面从几个方面来进行说明

  • hosts:定制执行task的服务器列表
  • roles:定义执行task的role列表
  • parallel:并行执行task
  • serial:串行执行task
  • task:定义一个task
  • runs_once:该task只执行一次

fabric 的 task

task就是fabric需要在远程服务器上执行的函数,在fabric中有3中方法定义一个task

  1. 默认情况下,fabfile中每一个函数都是一个task。
  2. 继承自fabric的task类,这种方式比较难用,不推荐。
  3. 使用fabric的task装饰器,这是使用fabric最快速的方式,也是推荐的用法。
 
  1. from fabric.api import *

  2.  
  3. env.user='root'

  4. env.password='mysql123'

  5.  
  6. @task

  7. def hello():

  8. run('echo hello')

  9.  
  10. def world():

  11. run('echo world')

PS:默认情况下,fabfile中的所有函数对象都是一个task,但是如果我们使用了task装饰器,显示的定义了一个task,那么,其他没有通过task装饰器装饰的函数将不会被认为是一个task。

fabric的host

为了方便我们的使用,fabric提供了非常灵活的方式指定对哪些远程服务器执行操作,根据我们前面的知识,我们知道有两种方式:通过env.hosts来执行,或者在fab执行命令的时候使用-H参数,除此之外,还有以下需要注意的地方

  1. 指定host时,可以同时指定用户名和端口号: username@hostname:port
  2. 通过命令行指定要多哪些hosts执行人物:fab mytask:hosts="host1;host2"
  3. 通过hosts装饰器指定要对哪些hosts执行当前task
  4. 通过env.reject_unkown_hosts控制未知host的行为,默认True,类似于SSH的StrictHostKeyChecking的选项设置为no,不进行公钥确认。
 
  1. from fabric.api import *

  2.  
  3. env.hosts = [

  4. '[email protected]:22',

  5. '[email protected]:22',

  6. '[email protected]:22'

  7. ]

  8. env.passwords = {

  9. '[email protected]:22':'123456201',

  10. '[email protected]:22':'123456202',

  11. '[email protected]:22':'123456203'

  12. }

  13.  
  14. @hosts('[email protected]:22')

  15. @task

  16. def hello():

  17. run('ifconfig br0')

  18.  
  19.  
  20. # 命令行的方式:

  21. fab hello:hosts="[email protected];[email protected]"

fabric的role

role是对服务器进行分类的手段,通过role可以定义服务器的角色,以便对不同的服务器执行不同的操作,Role逻辑上将服务器进行了分类,分类以后,我们可以对某一类服务器指定一个role名即可。进行task任务时,对role进行控制。

 
  1. # role在env.roledefs中进行定义

  2. env.roledefs = {

  3. 'web':['[email protected]','192.168.10.202'] # role名称为:web

  4. 'db':['[email protected]',] # role名称为:db

  5. }

  6.   当我们定义好role以后,我们就可以通过roles装饰器来指定在哪些role上运行task。

  7.  
  8.  
  9. from fabric.api import *

  10.  
  11. env.roledefs = {

  12. 'web':['[email protected]:22','[email protected]:22',],

  13. 'db':['[email protected]:22',]

  14. }

  15. env.passwords = {

  16. '[email protected]:22':'123456201',

  17. '[email protected]:22':'123456202',

  18. '[email protected]:22':'123456203'

  19. }

  20.  
  21. @roles('db') # 只对role为db的主机进行操作

  22. @task

  23. def hello():

  24. run('ifconfig br0')

注意:hosts 装饰器可以和 roles 装饰器一起使用(全集),看起来容易造成混乱,不建议混搭。

示例代码 2 :

 
  1. from fabric.api import env, roles, run, execute, cd

  2.  
  3. env.roledefs = {

  4. 'staging': ['[email protected]','[email protected]'],

  5. 'build': ['[email protected]']

  6. }

  7.  
  8. env.passwords = {

  9. 'staging': '11111',

  10. 'build': '123456'

  11. }

  12.  
  13. @roles('build')

  14. def build():

  15. with cd('/home/build/myapp/'):

  16. run('git pull')

  17. run('python setup.py')

  18.  
  19. @roles('staging')

  20. def deploy():

  21. run('tar xfz /tmp/myapp.tar.gz')

  22. run('cp /tmp/myapp /home/bjhee/www/')

  23.  
  24. def task():

  25. execute(build)

  26. execute(deploy)

现在让我们执行fab task,这时Fabric会先在一台build服务器上执行build任务,然后在两台staging服务器上分别执行deploy任务。”@roles”装饰器指定了它所装饰的任务会被哪个角色的服务器执行。

fabric的执行模型

fabric执行任务的步骤如下:

  1. 创建任务列表,这些任务就是 fab 命令行参数指定的任务,fab 会保持这些任务的顺序
  2. 对于每个任务,构造需要执行该任务的服务器列表,服务器列表可以通过命令行参数指定,或者 env.hosts 指定,或者通过hosts 和 roles 装饰器指定
  3. 遍历任务列表,对于每一台服务器分别执行任务,可以将任务列表和服务器列表看作是两个 for 循环,任务列表是外层循环,服务器列表是内存循环,fabric 默认是串行执行的可以通过装饰器或者命令行参数确定任务执行的方式
  4. 对于没有指定服务器的任务默认为本地任务,仅执行一次

PS:关于并行模式:

  1. 通过命令行参数 -P(--parallel) 通知 Fabric 并行执行 task
  2. 通过 env.parallel 设置设否需要并行执行
  3. 通过 parallel 装饰器通知 Fabric 并行执行 task,它接受一个 pool_size 作为参数(默认为0),表示可以有几个任务并行执行

并行执行

我们在介绍执行远程命令时曾提到过多台机器的任务默认情况下是串行执行的。Fabric支持并行任务,当服务器的任务之间没有依赖时,并行可以有效的加快执行速度。怎么开启并行执行呢?办法也是两个:

1. 在执行 ”fab” 命令时加上 ”-P” 参数:$ fab -P hello
2. 设置 ”env.parallel” 环境参数为 True

 
  1. from fabric.api import env

  2.  
  3. env.parallel = True

如果,我们只想对某一任务做并行的话,我们可以在任务函数上加上”@parallel”装饰器:

 
  1. from fabric.api import parallel

  2.  
  3. @parallel

  4. def runs_in_parallel():

  5. pass

  6.  
  7. def runs_serially():

  8. pass

这样即便并行未开启,”runs_in_parallel()”任务也会并行执行。反过来,我们可以在任务函数上加上”@serial”装饰器:

 
  1. from fabric.api import serial

  2.  
  3. def runs_in_parallel():

  4. pass

  5.  
  6. @serial

  7. def runs_serially():

  8. pass

这样即便并行已经开启,”runs_serially()”任务也会串行执行。

由于并行执行影响的最小单位是任务,所以功能的启用或禁用也是以任务为单位使用 parallel 或 serial 装饰器。如下:

 
  1. @parallel #将下面的函数设为并行执行。

  2. def runs_parallel():

  3. run('uname -r')

  4. @serial #将下面的函数设为顺序执行(默认即为顺序执行 )

  5. def runs_serially():

  6. pass

这样在执行时runs_parallel即为并行执行,serially为顺序执行。也可以在执行命令的时候指定:

 
  1. #fab parallel -P #-P用来指定并行执行

  2.  
  3. [192.168.122.103] run: uname -r

  4. [192.168.122.102] run: uname -r

  5. [192.168.122.101] run: uname -r

  6. [192.168.122.101] out: 3.10.0-514.el7.x86_64

  7. [192.168.122.101] out:

  8.  
  9. [192.168.122.102] out: 3.10.0-514.el7.x86_64

  10. [192.168.122.102] out:

  11.  
  12. [192.168.122.103] out: 3.10.0-514.el7.x86_64

  13. [192.168.122.103] out:

可以从上列返回值中很明显的看出并发执行与顺序执行的区别。

如果你的主机列表很多的时候,并行执行可能会分出几百个线程。这样对主机的压力是非常大的。这个时候需要限制线程的个数。默认是不限制的,即所有主机都会并发执行。可以使用pool_size来限制线程数。如下:

 
  1. @parallel(pool_size=5) #将下面的函数设为并行执行,并且限制最多5个线程。

  2. def runs_parallel():

  3. pass

输出管理

Fabric默认定义了几个输出层级:

层级名称 层级说明
status 状态信息,包括提示 Fabric 已结束运行、用户是否使用键盘中止操作、或者服务器是否断开了连接。通常来说这些信息都不会很冗长,但是至关重要。
aborts 终止信息。和状态信息一样,只有当 Fabric 做为库使用的时候才可能应该关闭,而且还并不一定。注意,即使该输出集被关闭了,并不能阻止程序退出——你只会得不到任何 Fabric 退出的原因。
warnings: 警报信息。通常在预计指定操作失败时会将其关闭,比如说你可能使用 grep 来测试文件中是否有特定文字。如果设置 env.warn_only 为 True 会导致远程程序执行失败时完全没有警报信息。和 aborts 一样,这项设置本身并不控制警报行为,仅用于是否输出警报信息。
running 执行信息,输出正在执行的命令或者正在传输的文件名称
stdout 标准输出,本地或远程的 stdout。来自命令行的非错误输出
stderr 错误输出,本地或远程的 stderr。比如命令中错误相关的输出

在使用中,Fabric默认尽可能多的将信息显示出来。也就是上列信息都会输出到屏幕上。但有些时候我们并不需要在意这么多信息,而且过多的信息会使我们很难抓住重点。这时候我们可以通过hide和show来进行输出控制:

 
  1. def my_task():

  2. with hide('running', 'stdout', 'stderr'): #hide表示隐藏,下面的命令隐藏running,stdout,stderr输出

  3. run('ls /var/www')

因为Fabric默认是打开所有输出的,show命令并不常用。但可以通过show命令开启debug模式:

 
  1. def remote_uname():

  2. with show("debug"): #打开debug输出,默认只有这项是关闭的

  3. run('uname -r')

执行脚本:

 
  1. [192.168.122.103] run: /bin/bash -l -c "uname -r"

  2. [192.168.122.102] run: /bin/bash -l -c "uname -r"

  3. [192.168.122.101] run: /bin/bash -l -c "uname -r"

之前的输出:

 
  1. [192.168.122.103] run: uname -r

  2. [192.168.122.102] run: uname -r

  3. [192.168.122.101] run: uname -r

相比于之前的输出,可以看出命令提示更加完整。

其他装饰器

前面介绍了task,hosts,roles和parallel装饰器,此外还有两个装饰器比较常用

  • runs_once:只执行一次,防止task被多次调用。例如,对目录打包进行上传,上传动作对不同的服务器可能会执行多次,但是打包的动作只需要执行一次即可。
  • serial:强制当前task穿行执行。使用该参数时优先级最高,即便是制定了并发执行的参数

runc_once 使用示例(查看本地与远程主机信息):

本示例调用local方法执行本地命令,添加@runs_once修饰符保证任务函数只执行一次,调用run方法执行远程命令。

 
  1. #!/usr/bin/env python

  2. # -*- encoding: utf-8 -*-

  3.  
  4. from fabric.api import *

  5.  
  6. env.user = 'root'

  7. env.hosts = ['192.168.1.22']

  8. env.password = '123456'

  9.  
  10. @runs_once #查看本地系统信息,当有多台主机时只运行一次

  11. def local_task(): #本地任务函数

  12. local('uname -a')

  13.  
  14. def remote_task():

  15. with cd('/var/logs'): #with的作用是让后面的表达式语句继承当前状态,实现:cd /var/logs && ls -l的效果

  16. run('ls -l')

  17.  
  18. simple1.py

执行:

        fab -f simple1.py local_task
        fab -f simple1.py remote_task

常用的功能函数

fabric中还有其他的一些好用的函数

封装task

fabric提供了一个execute函数,用来对task进行封装。它最大的好处就是可以将一个大的任务拆解为很多小任务,每个小任务互相独立,互不干扰

 
  1. from fabric.api import *

  2.  
  3. env.roledefs = {

  4. 'web':['[email protected]:22','[email protected]:22',],

  5. 'db':['[email protected]:22',]

  6. }

  7. env.passwords = {

  8. '[email protected]:22':'123456201',

  9. '[email protected]:22':'123456202',

  10. '[email protected]:22':'123456203'

  11. }

  12.  
  13. @roles('db')

  14. def hello():

  15. run('echo hello')

  16.  
  17. @roles('web')

  18. def world():

  19. run('echo world')

  20.  
  21. @task

  22. def helloworld():

  23. execute(hello)

  24. execute(world)

# 函数helloworld作为入口,分别调用两个task,对不同的主机进行操作

utils函数

包含一些辅助行的功能函数,这些函数位于fabric.utils下,常用的函数如下:

  1. abort:终止函数执行,打印错误信息到stderr,并且以退出码1退出。
  2. warn:输出警告信息,但是不会终止函数的执行
  3. puts:打印输出,类似于Python中的print函数
 
  1. def helloworld():

  2. execute(hello)

  3. abort('----->abort') # 执行到这里时,直接退出

  4. warn('----->warn') # 会发出提示信息,不会退出

  5. puts('----->puts') # 会打印括号中的信息

  6. execute(world)

带颜色的输出

fabric为了让输出日志更具有可读性,对命令行中断的颜色输出进行了封装,使用print打印带有不同颜色的文本,这些颜色包含在fabric.colors中。像warn,puts打印输出的,也可以直接渲染颜色

  • blue(text,blod=False)  蓝色
  • cyan(text,blod=False)  淡蓝色
  • green(text,blod=False)  绿色
  • magenta(text,blod=False)  紫色
  • red(text,blod=False)  红色
  • white(text,blod=False)  白色
  • yellow(text,blod=False)   黄色
 
  1. def ls(path='.'):

  2. run('ls {0}'.format(path))

  3.  
  4. def hello():

  5.  
  6. execute(hell) # task任务hell

  7. warn(yellow('----->warn')) # 会发出提示信息,不会退出

  8. puts(green('----->puts')) # 会打印括号中的信息

  9. execute(ls) # task任务ls

  10. print(green('the text is green')) # 单纯的渲染文字:

  11.  
  12. def hell(name='world'):

  13. print('hello %s' % name)

终端输出带颜色

我们习惯上认为绿色表示成功,黄色表示警告,而红色表示错误,Fabric 支持带这些颜色的输出来提示相应类型的信息:

 
  1. from fabric.colors import *

  2.  
  3. def hello():

  4. print green("Successful")

  5. print yellow("Warning")

  6. print red("Error")

示例代码 2(fabric_5.py):

 
  1. #!/usr/bin/env python

  2. # coding:utf-8

  3.  
  4. from fabric.colors import *

  5.  
  6. def show():

  7. print green('success')

  8. print red('fail')

  9. print yellow('yellow')

执行命令:[root@saltstack fabric]# fab -f fabric_5.py show

限制任务只能被执行一次

通过”execute()”方法,可以在一个”fab”命令中多次调用同一任务,如果想避免这个发生,就要在任务函数上加上”@runs_once”装饰器。

 
  1. from fabric.api import execute, runs_once

  2.  
  3. @runs_once

  4. def hello():

  5. print "Hello Fabric!"

  6.  
  7. def test():

  8. execute(hello)

  9. execute(hello)

现在不管我们”execute”多少次hello任务,都只会输出一次”Hello Fabric!”字样

更多内容请参阅Fabric的官方文档。本篇中的示例代码可以在这里下载

确认信息

有时候我们在某一步执行错误,会给用户提示,是否继续执行时,confirm就非常有用了,它包含在 fabric.contrib.console中

 
  1. def testconfirm():

  2.  
  3. result = confirm('Continue Anyway?')

  4. print(result)

  5.  
  6.  
  7. # 会提示输入y/n

  8. # y 时 result为True

  9. # n 时 result为False

使用Fabric源码安装redis

下载一个redis的包和fabfile.py放在同级目录即可,不同目录需要修改包的位置,这里使用的是redis-4.0.9版本。

 
  1. #!/usr/bin/env python3

  2. from fabric.api import *

  3. from fabric.contrib.console import confirm

  4. from fabric.utils import abort

  5. from fabric.colors import *

  6.  
  7. env.hosts = ['192.168.10.202',]

  8. env.user = 'root'

  9. env.password = '123456202'

  10.  
  11. @runs_once

  12. @task

  13. def test():

  14. with settings(warn_only=True):

  15. local('tar xf redis-4.0.9.tar.gz')

  16. with lcd('redis-4.0.9'):

  17. result = local('make test',capture=True)

  18. if result.failed and not confirm('Test is Faild Continue Anyway?'):

  19. abort('Aborting at user request.')

  20.  
  21. with lcd('redis-4.0.9'):

  22. local("make clean")

  23. local('tar zcvf redis-4.0.10.tar.gz redis-4.0.9')

  24.  
  25. @task

  26. def deploy():

  27. put('redis-4.0.10.tar.gz','/tmp/')

  28. with cd('/tmp'):

  29. run('tar xf redis-4.0.10.tar.gz')

  30. with cd('redis-4.0.9'):

  31. sudo('make install')

  32.  
  33. @task

  34. def start_redis():

  35. with settings(warn_only=True):

  36. result = run('netstat -lntup | grep -w redis-server')

  37. if result.return_code == 0:

  38. print(green('redis is started!'))

  39. else:

  40. run('set -m ; /usr/local/bin/redis-server &') # 用pty=False, fabric进程退不出来,不知道为啥,所以这里用set -m

  41. print(green('redis start Successful'))

  42.  
  43. @task

  44. def clean_local_file():

  45. local('rm -rf redis-4.0.10.tar.gz')

  46.  
  47. @task

  48. def clean_file():

  49. with cd('/tmp'):

  50. sudo('rm -rf redis-4.0.9')

  51. sudo('rm -rf redis-4.0.10.tar.gz')

  52.  
  53. @task

  54. def install():

  55. execute(test)

  56. execute(deploy)

  57. execute(clean_file)

  58. execute(clean_local_file)

  59. execute(start_redis)

PS:关于set -m 的作用如下:
 
"set -m" turns on job control, you can run processes in a separate process group.<br>理解:在一个独立的进程组里面运行我们的进程。

Fabric 使用示例:

form:https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/projects/autoOps/pythonSelf/fabfile.py

 
  1. #!/usr/bin/python

  2. # encoding: utf-8

  3. # -*- coding: utf8 -*-

  4.  
  5. # Pythonic remote execution

  6. # Refer: http://docs.fabfile.org/en/1.6/tutorial.html#conclusion

  7. # Refer: https://github.com/dlapiduz/fabistrano/blob/master/fabistrano/deploy.py

  8. # Refer: https://gist.github.com/mtigas/719452

  9. # Refer: http://docs.fabfile.org/en/1.12/usage/env.html

  10. # fab -i c:\Users\Guodong\.ssh\exportedkey201310171355 -f .\projects\autoOps\pythonSelf\fabfile.py dotask

  11.  
  12. import datetime

  13. import logging

  14. import logging.handlers

  15. import os

  16. import platform

  17. import re

  18. import sys

  19. import time

  20.  
  21. import requests

  22.  
  23.  
  24. def win_or_linux():

  25. # os.name ->(sames to) sys.builtin_module_names

  26. if 'posix' in sys.builtin_module_names:

  27. os_type = 'Linux'

  28. elif 'nt' in sys.builtin_module_names:

  29. os_type = 'Windows'

  30. return os_type

  31.  
  32.  
  33. def is_windows():

  34. if "windows" in win_or_linux().lower():

  35. return True

  36. else:

  37. return False

  38.  
  39.  
  40. def is_linux():

  41. if "linux" in win_or_linux().lower():

  42. return True

  43. else:

  44. return False

  45.  
  46.  
  47. def initLoggerWithRotate():

  48. current_time = time.strftime("%Y%m%d%H")

  49. logpath = "/tmp"

  50. logfile = "log_fabfile_" + current_time + ".log"

  51. if not os.path.exists(logpath):

  52. os.makedirs(logpath)

  53. else:

  54. logfile = os.path.join(logpath, logfile)

  55.  
  56. logger = logging.getLogger("fabric")

  57. log_formatter = logging.Formatter("%(asctime)s %(filename)s:%(lineno)d %(name)s %(levelname)s: %(message)s",

  58. "%Y-%m-%d %H:%M:%S")

  59. file_handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=104857600, backupCount=5)

  60. file_handler.setFormatter(log_formatter)

  61. stream_handler = logging.StreamHandler(sys.stderr)

  62. logger.addHandler(file_handler)

  63. logger.addHandler(stream_handler)

  64. logger.setLevel(logging.DEBUG)

  65. return logger

  66.  
  67.  
  68. logger = initLoggerWithRotate()

  69.  
  70. os_release = platform.system()

  71. if os_release == "Windows":

  72. pass

  73. elif os_release == "Linux":

  74. distname = platform.linux_distribution()[0]

  75. if str(distname).lower() == "ubuntu":

  76. command_to_execute = "which pip >/dev/null 2>&1 || apt-get -y install libcurl4-openssl-dev python-pip"

  77. os.system(command_to_execute)

  78. elif str(distname).lower() == "centos":

  79. command_to_execute = "which pip &>/dev/null 1>&2 || yum -y install python-pip"

  80. os.system(command_to_execute)

  81. else:

  82. print "Error => Unsupported OS type."

  83. logger.error("Unsupported OS type.")

  84. sys.exit(1)

  85.  
  86. try:

  87. from fabric.api import *

  88. except ImportError:

  89. try:

  90. command_to_execute = "pip install fabric"

  91. os.system(command_to_execute)

  92. except OSError:

  93. sys.exit(1)

  94. finally:

  95. from fabric.api import *

  96. from fabric.main import main

  97. from fabric.colors import *

  98. from fabric.context_managers import *

  99. from fabric.contrib.console import confirm

  100.  
  101. try:

  102. import pycurl

  103. except ImportError:

  104. try:

  105. command_to_execute = "pip install pycurl"

  106. os.system(command_to_execute)

  107. except OSError:

  108. sys.exit(1)

  109. import pycurl

  110.  
  111. try:

  112. import pytz

  113. except ImportError:

  114. try:

  115. command_to_execute = "pip install pytz"

  116. os.system(command_to_execute)

  117. except OSError:

  118. sys.exit(1)

  119. import pytz

  120.  
  121. try:

  122. import shutil

  123. except ImportError:

  124. try:

  125. command_to_execute = "pip install shutil"

  126. os.system(command_to_execute)

  127. except OSError:

  128. sys.exit(1)

  129. import shutil

  130.  
  131. try:

  132. import certifi

  133. except ImportError:

  134. try:

  135. command_to_execute = "pip install certifi"

  136. os.system(command_to_execute)

  137. except OSError:

  138. sys.exit(1)

  139. import certifi

  140.  
  141. env.roledefs = {

  142. 'test': ['[email protected]:22', ],

  143. 'nginx': ['[email protected]:22', '[email protected]:22', ],

  144. 'db': ['[email protected]:22', '[email protected]:22', ],

  145. 'sit': ['[email protected]:22', '[email protected]:22', '[email protected]:22', ],

  146. 'uat': ['[email protected]:22', '[email protected]:22', '[email protected]:22', ],

  147. 'all': ["10.6.28.27", "10.6.28.28", "10.6.28.35", "10.6.28.46", "10.6.28.93", "10.6.28.125", "10.6.28.135"]

  148. }

  149.  
  150. env.user = "root"

  151. env.hosts = ["10.6.28.27", "10.6.28.28", "10.6.28.35", "10.6.28.46", "10.6.28.93", "10.6.28.125", "10.6.28.135"]

  152. env.command_timeout = 15

  153. env.connection_attempts = 2

  154.  
  155.  
  156. def show_uname():

  157. try:

  158. out = run("uname -a")

  159. except KeyboardInterrupt:

  160. logger.warning("We catch 'Ctrl + C' pressed, task canceled!")

  161. sys.exit(1)

  162. if out.return_code == 0:

  163. logger.info("task finished successfully on " + env.host + " .")

  164. else:

  165. logger.error("task finished failed on " + env.host + " .")

  166.  
  167.  
  168. # Call method: ping:www.qq.com

  169. def ping(host):

  170. if host is not None:

  171. try:

  172. out = run("ping -c1 " + host + " >/dev/null 2>&1")

  173. except KeyboardInterrupt:

  174. logger.warning("We catch 'Ctrl + C' pressed, task canceled!")

  175. sys.exit(1)

  176. if out.return_code == 0:

  177. logger.info("task ping finished successfully on " + env.host + " .")

  178. else:

  179. logger.error("task ping finished failed on " + env.host + " .")

  180.  
  181.  
  182. def showDiskUsage():

  183. try:

  184. run("df -h")

  185. except KeyboardInterrupt:

  186. logger.warning("We catch 'Ctrl + C' pressed, task canceled!")

  187. sys.exit(1)

  188.  
  189.  
  190. def setNameServer(server=None):

  191. nameServerList = ""

  192. if isinstance(server, list) and len(server) >= 1:

  193. for host in server:

  194. nameServerList += ("namserver %s\n" % host)

  195. else:

  196. nameServerList = "nameserver 182.254.116.116\n"

  197.  
  198. print("Executing on %(host)s as %(user)s" % env)

  199. try:

  200. out = run('test -f /etc/resolv.conf && echo "%s" > /etc/resolv.conf' % nameServerList.strip('\n'))

  201. except KeyboardInterrupt:

  202. logger.warning("We catch 'Ctrl + C' pressed, task canceled!")

  203. sys.exit(1)

  204. if out.return_code == 0:

  205. logger.info("task finished successfully on " + env.host + " .")

  206. run('test -f /etc/resolv.conf && cat /etc/resolv.conf')

  207. else:

  208. logger.error("task finished failed on " + env.host + " .")

  209. abort("task finished failed on " + env.host + " .")

  210.  
  211.  
  212. def checkWeChatApi():

  213. qy_api = "qyapi.weixin.qq.com"

  214. api = "api.weixin.qq.com"

  215. ping(qy_api)

  216. ping(api)

  217.  
  218.  
  219. def showUptime():

  220. run("uptime")

  221.  
  222.  
  223. def putSelf():

  224. try:

  225. put(__file__, '/tmp/fabric.py')

  226. except Exception as e:

  227. logger.error("task putSelf failed! msg: %s" % e)

  228. abort("task putSelf failed! msg: %s" % e)

  229.  
  230.  
  231. def sudo_run(*args, **kwargs):

  232. if env.use_sudo is not None:

  233. sudo(*args, **kwargs)

  234. else:

  235. run(*args, **kwargs)

  236.  
  237.  
  238. def check_var_is_absent(var):

  239. if var is None or var == "":

  240. print var + " is None or empty, please check and fix it!"

  241. sys.exit(1)

  242.  
  243.  
  244. def check_runtime_dependencies():

  245. check_var_is_absent(env.basedir)

  246. pass

  247.  
  248.  
  249. def backup_file(path, extension='~'):

  250. backup_filename = path + '.' + extension

  251.  
  252. if os.path.islink(path):

  253. src = os.readlink(path)

  254. else:

  255. src = path

  256.  
  257. shutil.copy2(src, backup_filename)

  258.  
  259. return backup_filename

  260.  
  261.  
  262. def rollback_file(path, extension='~'):

  263. if os.path.islink(path):

  264. src = os.readlink(path)

  265. else:

  266. src = path

  267. if os.path.exists(src + extension):

  268. shutil.copy2(src + extension, src)

  269. return src

  270.  
  271.  
  272. def check_network_connectivity():

  273. internet_hostname = "www.aliyun.com"

  274. ping = 'ping -c4 ' + internet_hostname

  275. result_code = None

  276. try:

  277. run(ping)

  278. except Exception as _:

  279. del _

  280. result_code = 1

  281. if result_code is not None:

  282. print red("Error => connect to Internet failed!")

  283. logger.error("connect to Internet failed!")

  284. else:

  285. print green("Success => connect to Internet successfully!")

  286.  
  287.  
  288. def check_name_resolve():

  289. internet_hostname = "www.aliyun.com"

  290. nslookup = 'nslookup ' + internet_hostname

  291. result_code = None

  292. try:

  293. run(nslookup)

  294. except Exception as _:

  295. del _

  296. result_code = 1

  297. if result_code is not None:

  298. print red("Error => name resolve to Internet failed!")

  299. logger.error("name resolve to Internet failed!")

  300. else:

  301. print green("Success => name resolve to Internet successfully!")

  302.  
  303.  
  304. def set_dns_resolver():

  305. serverList = ['182.254.116.116', '202.106.196.115', '202.106.0.20']

  306. setNameServer(serverList)

  307.  
  308.  
  309. def set_hosts_file(hosts="/etc/hosts"):

  310. import socket

  311. if not os.path.exists(hosts):

  312. if not os.path.exists(os.path.dirname(hosts)):

  313. os.makedirs(os.path.dirname(hosts))

  314.  
  315. with open(hosts, "w") as f:

  316. hosts_url = "https://raw.githubusercontent.com/racaljk/hosts/master/hosts"

  317. conn = requests.head(hosts_url)

  318. if conn.status_code != 200:

  319. hosts_url = "https://coding.net/u/scaffrey/p/hosts/git/raw/master/hosts"

  320. curl = pycurl.Curl()

  321. curl.setopt(pycurl.URL, hosts_url)

  322. curl.setopt(pycurl.CAINFO, certifi.where())

  323. curl.setopt(pycurl.WRITEDATA, f)

  324. curl.perform()

  325. curl.close()

  326.  
  327. hostname = socket.gethostname() # socket.getfqdn()

  328. print hostname

  329. try:

  330. ip = socket.gethostbyname(socket.gethostname()) # TODO(Guodong Ding) Ubuntu not passed here, but CentOS passed!

  331. except Exception as _:

  332. del _

  333. ip = None

  334. with open(hosts, "a") as f:

  335. if ip is not None:

  336. appended_content = "\n" + "127.0.0.1 " + hostname + "\n" + ip + " " + hostname + "\n"

  337. else:

  338. appended_content = "\n" + "127.0.0.1 " + hostname + "\n"

  339. f.write(appended_content)

  340.  
  341.  
  342. def set_capistrano_directory_structure_over_fabric():

  343. print blue("setting capistrano directory structure ...")

  344. capistrano_release = env.basedir + '/release'

  345. capistrano_repository = env.basedir + '/repository'

  346. capistrano_share = env.basedir + '/share'

  347. capistrano_backup = env.basedir + '/backup'

  348. if os.path.exists(env.capistrano_ds_lock):

  349. pass

  350. else:

  351. if not os.path.exists(capistrano_release):

  352. os.makedirs(capistrano_release)

  353. if not os.path.exists(capistrano_repository):

  354. os.makedirs(capistrano_repository)

  355. if not os.path.exists(capistrano_share):

  356. os.makedirs(capistrano_share)

  357. if not os.path.exists(capistrano_backup):

  358. os.makedirs(capistrano_backup)

  359.  
  360. with open(env.capistrano_ds_lock, 'w') as f:

  361. if os.path.exists("/etc/timezone"):

  362. tz = file("/etc/timezone").read().strip()

  363. if tz == 'Asia/Chongqing' or tz == 'Asia/Shanghai':

  364. content = datetime.datetime.now(tz=pytz.timezone(tz))

  365. else:

  366. content = datetime.datetime.now(tz=pytz.timezone('Asia/Shanghai'))

  367. else:

  368. content = datetime.datetime.now()

  369. f.write(str(content))

  370. print green("setting capistrano directory structure successfully!")

  371.  
  372.  
  373. def git_clone_local():

  374. code_dir = env.basedir + '/repository'

  375. git_clone = "git clone " + env.git_address + " " + code_dir

  376. local(git_clone)

  377.  
  378.  
  379. def terminal_debug(defName):

  380. command = "fab -i c:\Users\Guodong\.ssh\exportedkey201310171355\

  381. -f C:/Users/Guodong/PycharmProjects/LinuxBashShellScriptForOps/projects/autoOps/pythonSelf/fabfile.py \

  382. %s" % defName

  383. os.system(command)

  384.  
  385.  
  386. if __name__ == '__main__':

  387. if len(sys.argv) == 1 and is_windows():

  388. logger.info("Started.")

  389. terminal_debug("showUptime showDiskUsage")

  390. sys.exit(0)

  391.  
  392. sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])

  393. print red("Please use 'fab -f %s'" % " ".join(str(x) for x in sys.argv[0:]))

  394. logger.error("Syntax error. Exit now.")

  395. sys.exit(1)

部署脚本代码 1:

 
  1. #!/usr/bin/env python

  2. # -*- coding: utf-8 -*-

  3.  
  4. from datetime import datetime

  5. from fabric.api import *

  6.  
  7. # 登录用户和主机名:

  8. env.user = 'root'

  9. env.hosts = ['www.example.com'] # 如果有多个主机,fabric会自动依次部署

  10.  
  11. def pack():

  12. ' 定义一个pack任务 '

  13. # 打一个tar包:

  14. tar_files = ['*.py', 'static/*', 'templates/*', 'favicon.ico']

  15. local('rm -f example.tar.gz')

  16. local('tar -czvf example.tar.gz --exclude=\'*.tar.gz\' --exclude=\'fabfile.py\' %s' % ' '.join(tar_files))

  17.  
  18. def deploy():

  19. ' 定义一个部署任务 '

  20. # 远程服务器的临时文件:

  21. remote_tmp_tar = '/tmp/example.tar.gz'

  22. tag = datetime.now().strftime('%y.%m.%d_%H.%M.%S')

  23. run('rm -f %s' % remote_tmp_tar)

  24. # 上传tar文件至远程服务器:

  25. put('shici.tar.gz', remote_tmp_tar)

  26. # 解压:

  27. remote_dist_dir = '/srv/www.example.com@%s' % tag

  28. remote_dist_link = '/srv/www.example.com'

  29. run('mkdir %s' % remote_dist_dir)

  30. with cd(remote_dist_dir):

  31. run('tar -xzvf %s' % remote_tmp_tar)

  32. # 设定新目录的www-data权限:

  33. run('chown -R www-data:www-data %s' % remote_dist_dir)

  34. # 删除旧的软链接:

  35. run('rm -f %s' % remote_dist_link)

  36. # 创建新的软链接指向新部署的目录:

  37. run('ln -s %s %s' % (remote_dist_dir, remote_dist_link))

  38. run('chown -R www-data:www-data %s' % remote_dist_link)

  39. # 重启fastcgi:

  40. fcgi = '/etc/init.d/py-fastcgi'

  41. with settings(warn_only=True):

  42. run('%s stop' % fcgi)

  43. run('%s start' % fcgi)

猜你喜欢

转载自blog.csdn.net/hhd1988/article/details/108274044
今日推荐