码迷,mamicode.com
首页 > 编程语言 > 详细

Python2.7 fabric理论学习

时间:2014-12-08 19:29:36      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:http   io   ar   color   os   使用   sp   for   strong   

在python中有一个可以实现批量管理服务器的工具:fabric,在本地和远程机器上提供了一些基本的操作,并且可以上传/下载文件、执行sudo等功能。

       学习环境:ubuntu 12.10+python2.7

      安装fabric:

             1 通过apt安装,apt-get install fabric 此版本是1.4.2

             2 通过pip安装,pip install  fabric   此版本是1.5.1,pip命令在python-pip包中

farbic的环境变量:

     fabric的环境变量有很多,存放在一个字典中,fabric.state.env,而它包含在fabric.api中,为了方便,我们一般使用env来指代环境变量。env环境变量可以控制很多fabric的行为,一般通过env.xxx可以进行设置。

     fabric默认使用本地用户通过ssh进行连接远程机器,不过你可以通过env.user变量进行覆盖。当你进行ssh连接时,fabric会让你交互的让你输入远程机器密码,如果你设置了env.password变量,则就不需要交互的输入密码。

     下面介绍一些常用的环境变量:

     abort_on_prompts    设置是否运行在交互模式下,例如会提示输入密码之类,默认是false
     connection_attempts    fabric尝试连接到新服务器的次数,默认1次
     cwd    目前的工作目录,一般用来确定cd命令的上下文环境
     disable_known_hosts    默认是false,如果是true,则会跳过用户知道的hosts文件
     exclude_hosts    指定一个主机列表,在fab执行时,忽略列表中的机器
     fabfile    默认值是fabfile.py在fab命令执行时,会自动搜索这个文件执行。
     host_string    当fabric连接远程机器执行run、put时,设置的user/host/port等
     hosts    一个全局的host列表
     keepalive    默认0 设置ssh的keepalive
     loacl_user    一个只读的变量,包含了本地的系统用户,同user变量一样,但是user可以修改
     parallel    默认false,如果是true则会并行的执行所有的task
     pool_size    默认0 在使用parallel执行任务时设置的进程数
     password    ssh远程连接时使用的密码,也可以是在使用sudo时使用的密码
     passwords    一个字典,可以为每一台机器设置一个密码,key是ip,value是密码
     path    在使用run/sudo/local执行命令时设置的$PATH环境变量
     port    设置主机的端口
     roledefs    一个字典,设置主机名到规则组的映射
     roles    一个全局的role列表
     shell    默认是/bin/bash -1 -c 在执行run命令时,默认的shell环境
     skip_bad_hosts    默认false,为ture时,会导致fab跳过无法连接的主机
     sudo_prefix    默认值"sudo -S -p ‘%(sudo_prompt)s‘ " % env 执行sudo命令时调用的sudo环境
     sudo_prompt    默认值"sudo password:"
     timeout    默认10 网络连接的超时时间
     user   ssh使用哪个用户登录远程主机

 

fabric的执行模式:

      执行策略:fabric默认是单一的,串行的执行函数,虽然有一个paralle模式可供你选择。默认的行为遵循以下优先级规则:

          1 一个task列表被创建,通过命令行传递给fab
          2 针对每一个task,都有一个主机列表通过变量设置
          3 task列表按顺序执行每个task在主机列表中的主机上执行一遍
          4 如果主机列表为空,则默认在本地执行,也是执行一次

      设置主机列表的方法:

          1 hosts,在上下文环境中我们称hosts为“host strings”,strings指定了username、hostname、port等组合username@hostname:port。username和port可以省略,则默认使用本地用户和22端口。

          2 roles,host strings映射单个主机,但是有时候你想把一批主机加入一个组中,roles则提供了一个定义一系列主机的方法,这个映射可以通过env.rolesdefs来设置,它必须通过fabfile进行设置才可以使用。env.roledefs[‘webservers‘] = [‘www1‘, ‘www2‘, ‘www3‘]。

       怎样实际构造主机列表:

          1 通过全局变量env:env.hosts = [‘host1‘, ‘host2‘]
          2 通过命令行全局设置:fab -H IP1,IP2 Task。效果和env.hosts一样

          全局设置主机列表,只有在你需要所有的task运行在相同的主机上时。如果每个主机运行的task不一样呢?
          3 在命令行为每个task设置主机列表:fab mytask:hosts="host1;host2"

          如果一个task总是运行在预先固定好的主机上面,你可能希望把这些主机在fabfile中指定到固定的task上。这个功能可以通过hosts或者roles实现。
          4 在fabfile内部为每个task设施主机列表。在下面的模式下即使设置了-H或者env.hosts也会被忽略掉,但是不会忽略在命令行针对每个task的设置。
         @hosts(‘host1‘, ‘host2‘)
         def mytask():
             run(‘ls /var/www‘)

       主机列表的生效顺序如下:先单个task,再全局list

          1 fab mytask:host=host1
          2 @hosts(‘host1‘)
          3 env.hosts = [‘host1‘]
          4 --hosts=host1

        排除指定的主机:fab exclude_hosts="a;b" 或者 -x a,b

        使用execute执行task:

           目前接触到得都是通过fab设置task来执行,我们也可以伪装task就像在fabfile中的元数据一样,不用通过fab设置运行task

        @roles(‘db‘)
        def migrate():
            pass
        def deploy():
            pass  
        execute(migrate)

fab 选项和参数:fab可以在命令行设置一些参数来影响fabric的行为,作用和设置fab环境变量一样

    -a, --no_agent    env.no_agent=true
    -A, --forward-agent    env.foward_agent=true
    --abort-on-prompts     env.abort_on_prompts=true
    -d COMMAND, --display=COMMAND
    --connection-attempts=M, -n M     env.connection_attempts=M
    -f FABFILE, --fabfile=FABFILE  默认fabfile.py
    -H HOSTS, --hosts=HOSTS     env.hosts=hosts
    -x HOSTS, --exclude-hosts=HOSTS     env.exclude_hosts=host
    --keepalive=KEEPALIVE    env.keepalive=KEEPALIVE
    -l, --list
    -p PASSWORD, --password=PASSWORD   env.password 
    -P, --parallel   env.parallel =true
    -R ROLES, --roles=ROLES   env.roles 
    -s SHELL, --shell=SHELL   env.shell 
    --skip-bad-hosts   env.skip_bad_hosts
    --timeout=N, -t N   env.timeout
    -u USER, --user=USER   env.user 
    -z, --pool-size   env.pool_size

    Because Fabric is just Python, you can import its components any way you want. However, for the purposes of encapsulation and convenience (and to make life easier for Fabric’s packaging script) Fabric’s public API is maintained in the fabric.api module.

     from fabric.api import *

core API:

1 打印带颜色的字符串

   from fabric.colors import *
   print(green("This text is green!"))

2 一些基本操作

   fabric.operations.get(remote_path, local_path=None)
   Download one or more files from a remote host.remote可以是目录或者文件,cd 远程机器  lcd本地机器

   fabric.operations.local(command, capture=False, shell=None)
   Run a command on the local system. 运用subprocess在shell=true的情况下执行命令。

   fabric.operations.open_shell(command=None)
   Invoke a fully interactive shell on the remote end.交互式的调用远程终端的shell

   fabric.operations.prompt(text, key=None, default=‘‘, validate=None)
   Prompt user with text and return the input (like raw_input).

   fabric.operations.put(local_path=None, remote_path=None, use_sudo=False,mirror_local_mode=False, mode=None)
   Upload one or more files to a remote host. 上传一个或者多个文件,local_path本地文件或者目录,

   fabric.operations.reboot(wait=120)
   Reboot the remote system.

   fabric.operations.run(command, shell=True, pty=True, combine_stderr=None, quiet=False, warn_only=False, stdout=None, stderr=None)
   Run a shell command on a remote host.

   fabric.operations.sudo(command, shell=True, pty=True, combine_stderr=None, user=None, quiet=False, warn_only=False, stdout=None, stderr=None, group=None)
   Run a shell command on a remote host, with superuser privileges.

3 上下文环境管理,主要使用with语句

   fabric.context_managers.cd(path)
   Context manager that keeps directory state when calling remote operations,可以在run sudo get put中使用,cd只能使用在远程服务器上,本地使用lcd。
   with cd(‘/var/www‘):
       run(‘ls‘) # cd /var/www && ls

    fabric.context_managers.lcd(path)
    Context manager for updating local current working directory.同cd,不过是在本地改变目录

    fabric.context_managers.path(path, behavior=‘append‘)
    Append the given path to the PATH used to execute any wrapped commands

    fabric.context_managers.prefix(command)
    Prefix all wrapped run/sudo commands with given command plus &&.在run或者sudo执行的命令前加前缀,通过&&进行连接

    fabric.context_managers.settings(*args, **kwargs)
    Nest context managers and/or override env variables.

4 有趣的工具

   fabric.contrib.project.rsync_project(*args, **kwargs)
   Synchronize a remote directory with the current project directory via rsync

   fabric.contrib.project.upload_project(local_dir=None, remote_dir=‘‘)
   Upload the current project to a remote system via tar/gzip

为了不误导大家,一些英文未翻译,参看官方文档:http://docs.fabfile.org/en/1.5/#documentation

Python2.7 fabric理论学习

标签:http   io   ar   color   os   使用   sp   for   strong   

原文地址:http://www.cnblogs.com/zhepama/p/4151719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!