Python模块之Fabric
Fabric简介
Fabric是一个Python库,可以通过SSH在多个host上批量执行任务。你可以编写任务脚本,然后通过Fabric在本地就可以使用SSH在大量远程服务器上自动运行。这些功能非常适合应用的自动化部署,或者执行系统管理任务。
官网:http://www.fabfile.org/
中文站点:http://fabric-chs.readthedocs.io/zh_CN/chs/
Fabric常用环境变量
fabric的环境变量有很多,存放在一个字典中,fabric.state.env,而它包含在fabric.api中,为了方便,我们一般使用env来指代环境变量。env环境变量可以控制很多fabric的行为,一般通过env.xxx可以进行设置。
fabric默认使用本地用户通过ssh进行连接远程机器,不过你可以通过env.user变量进行覆盖。当你进行ssh连接时,fabric会让你交互的让你输入远程机器密码,如果你设置了env.password变量,则就不需要交互的输入密码。
常用的环境变量:
>>> import fabric.api >>> for i in fabric.api.env: ... print(i) ... disable_known_hosts # 默认是false,如果是true,则会跳过用户知道的hosts文件 effective_roles tasks linewise show password # 定义密码 key_filename abort_on_prompts skip_unknown_tasks reject_unknown_hosts skip_bad_hosts # 默认false,为ture时,会导致fab跳过无法连接的主机 use_ssh_config roledefs # 定义角色分组,例如:区分DB主机与web主机 gateway # 定义网关(中转,堡垒机)IP gss_auth keepalive eagerly_disconnect rcfile path_behavior hide sudo_prefix lcwd no_agent forward_agent remote_interrupt port # 定义目标主机的端口 shell version use_exceptions_for connection_attempts hosts # 定义目标主机 gss_deleg cwd abort_exception real_fabfile passwords # 与password功能一致,区别在于不同主机不同密码的应用场景 sudo_password host_string shell_env always_use_pty colorize_errors exclude_hosts # 排除指定主机 all_hosts sudo_prompt again_prompt echo_stdin user # 定义ssh使用哪个用户登录远程主机 gss_kex command_timeout path local_user combine_stderr command_prefixes dedupe_hosts warn_only no_keys sudo_passwords roles fabfile use_shell host pool_size system_known_hosts prompts output_prefix command timeout # 默认10 网络连接的超时时间 default_port ssh_config_path parallel sudo_user ok_ret_codes
Fabric执行模式
执行策略:fabric默认是单一的,串行的执行函数,虽然有一个paralle模式可供你选择。默认的行为遵循以下优先级规则:
- 一个task列表被创建,通过命令行传递给fab
- 针对每一个task,都有一个主机列表通过变量设置
- task列表按顺序执行每个task在主机列表中的主机上执行一遍
- 如果主机列表为空,则默认在本地执行,也是执行一次
Fabric常用API
[root@bogon fabric]# python Python 2.6.6 (r266:84292, Jul 23 2015, 14:41:34) [GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import tab >>> import fabric.api >>> for i in dir(fabric.api): ... print(i) ... __builtins__ __doc__ __file__ __name__ __package__ abort cd # 切换远程目录 env execute fastprint get # 从远程主机下载文件到本地 hide hosts lcd # 切换本地目录 local # 执行本地命令 open_shell output parallel path prefix prompt # 获取用户输入信息 put # 上传本地文件到远程主机 puts quiet reboot remote_tunnel require roles run # 执行远程命令 runs_once # 函数修饰符 标识的函数只会执行一次,不收多台主机影响 serial settings shell_env show sudo # sudo方式执行远程命令 task # 函数修饰符,标识的函数为fab可以调用 warn warn_only with_settings
API应用场景案例
案例1:同时查看本地及远程主机信息
案例2:动态获取远程目录列表
案例3:网关模式文件的上传与下载
Fabric安装及使用
Fabric安装
pip install fabric
easy_install fabric
or
源码安装
fab命令默认被安装到Python的目录下,需要创建软链接
[root@saltstack ~]# find / -type f -name "fab"
/usr/local/python2.7.10/bin/fab
[root@saltstack ~]# ln -s /usr/local/python2.7.10/bin/fab /usr/bin/fab
[root@saltstack fabric]# fab -h Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ... Options: -h, --help show this help message and exit -d NAME, --display=NAME print detailed info about command NAME -F FORMAT, --list-format=FORMAT formats --list, choices: short, normal, nested -I, --initial-password-prompt Force password prompt up-front --initial-sudo-password-prompt Force sudo password prompt up-front -l, --list print list of possible commands and exit # 显示一个脚本中可用的task(命令) --set=KEY=VALUE,... comma separated KEY=VALUE pairs to set Fab env vars --shortlist alias for -F short --list -V, --version show program's version number and exit -a, --no_agent don't use the running SSH agent -A, --forward-agent forward local agent to remote end --abort-on-prompts abort instead of prompting (for password, host, etc) -c PATH, --config=PATH specify location of config file to use --colorize-errors Color error output -D, --disable-known-hosts do not load user known_hosts file -e, --eagerly-disconnect disconnect from hosts as soon as possible -f PATH, --fabfile=PATH python module file to import, e.g. '../other.py' # 指定入口文件,fab默认入口文件是:fabfile/fabfile.py -g HOST, --gateway=HOST gateway host to connect through # 指定网关(中转)设备,比如堡垒机环境,填写堡垒机IP即可 --gss-auth Use GSS-API authentication --gss-deleg Delegate GSS-API client credentials or not --gss-kex Perform GSS-API Key Exchange and user authentication --hide=LEVELS comma-separated list of output levels to hide -H HOSTS, --hosts=HOSTS comma-separated list of hosts to operate on # 指定host,支持多host逗号分开 -i PATH path to SSH private key file. May be repeated. -k, --no-keys don't load private key files from ~/.ssh/ --keepalive=N enables a keepalive every N seconds --linewise print line-by-line instead of byte-by-byte -n M, --connection-attempts=M make M attempts to connect before giving up --no-pty do not use pseudo-terminal in run/sudo -p PASSWORD, --password=PASSWORD password for use with authentication and/or sudo -P, --parallel default to parallel execution method # 以异步并行方式运行多主机任务,默认是串行 --port=PORT SSH connection port -r, --reject-unknown-hosts reject unknown hosts --sudo-password=SUDO_PASSWORD password for use with sudo only --system-known-hosts=SYSTEM_KNOWN_HOSTS load system known_hosts file before reading user known_hosts -R ROLES, --roles=ROLES comma-separated list of roles to operate on # 指定role,支持多个,即以角色名区分不同业务组设备 -s SHELL, --shell=SHELL specify a new shell, defaults to '/bin/bash -l -c' --show=LEVELS comma-separated list of output levels to show --skip-bad-hosts skip over hosts that can't be reached --skip-unknown-tasks skip over unknown tasks --ssh-config-path=PATH Path to SSH config file -t N, --timeout=N set connection timeout to N seconds # 设置设备连接超时时间(秒) -T N, --command-timeout=N set remote command timeout to N seconds # 设置远程主机命令执行超时时间(秒) -u USER, --user=USER username to use when connecting to remote hosts -w, --warn-only warn, instead of abort, when commands fail # warn_only,默认是碰到异常直接abort退出,该设置为发出告警,但不退出 -x HOSTS, --exclude-hosts=HOSTS comma-separated list of hosts to exclude -z INT, --pool-size=INT number of concurrent processes to use in parallel mode
Fabric应用案例
案例1:本地执行一组操作
# 直接用命令行的形式执行远程命令
[root@bogon fabric]# fab -p 'strong' -H 192.168.80.128 -- 'uname -m'
[192.168.80.128] Executing task '<remainder>'
[192.168.80.128] run: uname -m
[192.168.80.128] out: i686
[192.168.80.128] out:
Done.
Disconnecting from 192.168.80.128... done.
[root@saltstack fabric]# cat fabric_8.py #!/usr/bin/env python # coding:utf-8 from fabric.api import local def prepare_deploy(): local("./manage.py test my_app") local("git add -p && git commit") local("git push") [root@saltstack fabric]# fab -f fabric_8.py prepare_deploy # 报错是因为测试环境不足所致 [localhost] local: ./manage.py test my_app /bin/sh: ./manage.py: 没有那个文件或目录 Fatal error: local() encountered an error (return code 127) while executing './manage.py test my_app' Aborting.
案例2:远程查看服务器类型
[root@saltstack fabric]# cat fabric_1.py #!/usr/bin/env python # coding:utf-8 from fabric.api import run def host_type(): run('uname -s') # 注:fabfile.py为fab默认识别的文件名,如果不是该文件名需要使用-f参数说明要执行的文件名 [root@saltstack fabric]# fab -H localhost -f fabric_1.py host_type [localhost] Executing task 'host_type' [localhost] run: uname -s [localhost] out: Linux [localhost] out: Done. Disconnecting from localhost... done.
案例3:远程传递参数(本地执行原理一致)
[root@saltstack fabric]# cat fabric_2.py #!/usr/bin/env python # coding:utf-8 from fabric.api import run def host_type(name): run('uname -s') print("Hello %s !!!" % name) [root@saltstack fabric]# fab -H localhost -f fabric_2.py host_type:name=mads [localhost] Executing task 'host_type' [localhost] run: uname -s [localhost] out: Linux [localhost] out: Hello mads !!! Done. Disconnecting from localhost... done.
案例4:多台服务器批量执行相同的操作
[root@saltstack fabric]# cat fabric_3.py #!/usr/bin/env python # coding:utf-8 from fabric.api import run,cd,env,hosts env.hosts=['192.168.20.140:22','172.16.1.150:22'] # env.hosts=['user@ip:port',] ssh要用到的参数格式 env.password='strong' def host_type(): with cd('/tmp/'): run('du -ksh *') [root@saltstack fabric]# fab -f fabric_3.py host_type [192.168.20.140:22] Executing task 'host_type' [192.168.20.140:22] run: du -ksh * [192.168.20.140:22] out: 36K hsperfdata_rundeck [192.168.20.140:22] out: 8.0K pip-3wB4vO-unpack [192.168.20.140:22] out: 4.0K rundeck [192.168.20.140:22] out: 4.0K yum_save_tx-2016-07-30-20-49HgACou.yumtx [192.168.20.140:22] out: [172.16.1.150:22] Executing task 'host_type' [172.16.1.150:22] run: du -ksh * [172.16.1.150:22] out: 4.0K uname.txt [172.16.1.150:22] out: Done. Disconnecting from 172.16.1.150... done. Disconnecting from 192.168.20.140... done.
案例5:多台服务器混合,需要在不同服务器进行不同操作时
[root@saltstack fabric]# cat fabric_4.py #!/usr/bin/env python # coding:utf-8 from fabric.api import env,roles,run,execute env.roledefs = { 'server1': ['root@172.16.1.140:22',], 'server2': ['root@172.16.1.150:22', ] } env.password = 'strong' @roles('server1') def task1(): run('ls /home/ -l | wc -l') @roles('server2') def task2(): run('du -sh /home') def test(): # 调节主机组和主机组执行操作的顺序 execute(task2) execute(task1) [root@saltstack fabric]# fab -f fabric_4.py test [root@172.16.1.150:22] Executing task 'task2' [root@172.16.1.150:22] run: du -sh /home [root@172.16.1.150:22] out: 4.0K /home [root@172.16.1.150:22] out: [root@172.16.1.140:22] Executing task 'task1' [root@172.16.1.140:22] run: ls /home/ -l | wc -l [root@172.16.1.140:22] out: 3 [root@172.16.1.140:22] out: Done. Disconnecting from 172.16.1.150... done. Disconnecting from 172.16.1.140... done.
扩展
扩展1:打印颜色
[root@saltstack fabric]# cat fabric_5.py #!/usr/bin/env python # coding:utf-8 from fabric.colors import * def show(): print green('success') print red('fail') print yellow('yellow') [root@saltstack fabric]# fab -f fabric_5.py show success fail yellow Done.
效果图:
扩展2:错误及异常
默认,一组命令,上一个命令执行失败后,不会接着往下执行,失败后也可以进行不一样的处理,详解文档
# 默认情况 [root@saltstack fabric]# cat fabric_6.py #!/usr/bin/env python # coding:utf-8 #from fabric.api import run from fabric.api import local def host_type(): local('uname -s') local('tt') local('hostname')
[root@saltstack fabric]# fab -H localhost -f fabric_6.py host_type [localhost] Executing task 'host_type' [localhost] local: uname -s Linux [localhost] local: tt /bin/sh: tt: command not found Fatal error: local() encountered an error (return code 127) while executing 'tt' Aborting. # 注:由于tt执行报错,后面的hostname命令没有被执行 [root@saltstack fabric]# cat fabric_7.py #!/usr/bin/env python # coding:utf-8 from __future__ import with_statement from fabric.api import local, settings, abort from fabric.colors import * from fabric.contrib.console import confirm def host_type(): local('uname -s') with settings(warn_only=True): result = local('tt', capture=True) if result.failed and not confirm(red("tt cmd failed. Continue anyway?")): abort("Aborting at user request.") local('hostname') [root@saltstack fabric]# fab -H localhost -f fabric_7.py host_type [localhost] Executing task 'host_type' [localhost] local: uname -s Linux [localhost] local: tt Warning: local() encountered an error (return code 127) while executing 'tt' tt cmd failed. Continue anyway? [Y/n] y # 判断上一步执行有无异常,异常给予提示,确认是否继续 [localhost] local: hostname saltstack Done.
扩展3:密码管理
1)Fabric既支持ssh公钥认证也支持管理密码的机制
2)Fabric的密码管理机制提供了两层密码。如果你的server有相同的密码,可以在env.password中设置默认的密码;如果server密码不同,还可以在env.passwords中设置(host,password)对,为每个server设置单独的ssh密码。
小结
使用Fabric,你可以管理一系列host的SSH连接(包括主机名,用户,密码),定义一系列的任务函数,然后灵活的指定在哪些host上执行哪些任务。这非常使用于需要管理大量host的场景,比如运维,私有云管理,应用自动化部署等。
本文只是一篇入门文档,远没有体现出Fabric的强大。实际上,Fabric还包括大量的功能,比如Role的定义,远程交互及异常处理,并发执行,文件操作等,并且不仅仅局限于命令行方式,可以在你的应用中调用Fabric。
希望本文能够引起你对Fabric的兴趣,并在你的实际应用中解决问题。
出处:http://www.cnblogs.com/madsnotes/
声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。