Python2.7 Fabric Theory Learning

Source: Internet
Author: User

There is a tool in Python that allows you to manage your servers in bulk: Fabric, which provides basic operations on local and remote machines, and can upload/download files, execute sudo, and more.

Learning Environment: Ubuntu 12.10+python2.7

Install Fabric:

1 installation via apt, apt-get install fabric This version is 1.4.2

2 through PIP installation, Pip install fabric This version is the 1.5.1,PIP command in the PYTHON-PIP package

Environment variables for farbic:

The environment variables of the fabric are many, stored in a dictionary, fabric.state.env, and it is included in the FABRIC.API, for convenience, we generally use env to refer to environment variables. The ENV environment variable can control many of the fabric's behavior and can be set by env.xxx generally.

Fabric uses SSH to connect remote machines by default with local users, but you can overwrite them with env.user variables. When you make an SSH connection, fabric allows you to interactively enter the remote machine password, and if you set the Env.password variable, you do not need to enter the password interactively.

Here are some common environment variables:

Abort_on_prompts whether the settings are running in interactive mode, such as prompting for a password, the default is False
Connection_attempts fabric attempts to connect to the new server, default 1 times
CWD Current working directory, generally used to determine the context of the CD command
Disable_known_hosts default is False, if true, the hosts file that the user knows will be skipped
exclude_hosts Specifies a list of hosts that, when executed by the FAB, ignores the machines in the list
The Fabfile default value is fabfile.py when the Fab command executes, the file is automatically searched for execution.
Host_string when a fabric connects a remote machine to run, put, set user/host/port, etc.
Hosts a global host list
KeepAlive default 0 settings for SSH keepalive
Loacl_user A read-only variable that contains the local system user, same as the user variable, but user can modify
Parallel default False, if true, all tasks are executed in parallel
Pool_size default 0 Number of processes to set when performing tasks with parallel
Password The password used when SSH is connected remotely, or a password to use when using sudo
Passwords A dictionary, you can set a password for each machine, key is Ip,value is the password
The $PATH environment variable that path is set when you execute a command with run/sudo/local
Port to set the ports of the host
Roledefs A dictionary, setting host names to rule group mappings
Roles a global Role list
Shell default is/bin/bash-1-C when executing the Run command, the default shell environment
Skip_bad_hosts default False, Ture causes Fab to skip hosts that cannot connect
Sudo_prefix Default Value "Sudo-s-P '% (sudo_prompt) S '"% env execute sudo command when calling sudo environment
Sudo_prompt default value "sudo password:"
Timeout default 10 network connection time-out
User SSH uses which users log on to the remote host

Fabric's Execution Mode:

Execution policy: Fabric defaults to a single, serial execution function, although there is a Paralle mode available for you to choose from. The default behavior follows the following precedence rules:

11 task lists are created and passed to fab through the command line
2 for each task, there is a list of hosts that are set by variable
3 The Task list executes each task sequentially on the host in the host list
4 If the host list is empty, it is executed locally by default and is executed once

To set up a host list method:

1 hosts, in the context we call the hosts "host strings", strings designated username, hostname, port and other combinations [email protected]:p ort. Username and port can be omitted, the local user and port 22 are used by default.

2 Roles,host strings maps a single host, but sometimes you want to add a batch of hosts to a group, roles provides a way to define a series of hosts, This mapping can be set by Env.rolesdefs, which must be set through Fabfile to be used. env.roledefs[' webservers ' = [' www1 ', ' www2 ', ' www3 '].

How to actually construct the host list:

1 via global variable env:env.hosts = [' host1 ', ' host2 ']
2 Global Settings via command line: Fab-h ip1,ip2 Task. The same effect as env.hosts

Set the list of hosts globally only when you need all of the tasks running on the same host. What if each host is running a different task?
3 Set host list in command behavior per task: Fab mytask:hosts= "Host1;host2"

If a task is always running on a pre-pinned host, you may want to assign these hosts to a fixed task in fabfile. This function can be implemented through hosts or roles.
4 within Fabfile for each task facility host list. In the following mode, even if H is set or env.hosts is ignored, the settings for each task on the command line are not ignored.
@hosts (' host1 ', ' host2 ')
Def mytask ():
Run (' ls/var/www ')

The list of hosts takes effect in the following order: Single task first, global list

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

Exclude the specified host: Fab exclude_hosts= "A;b" or-X A, B

To execute a task using execute:

The current exposure is performed through the Fab setup task, and we can disguise the task as if it were metadata in Fabfile, without running the task through the FAB setup.

@roles (' db ')
Def migrate ():
Pass
def deploy ():
Pass
Execute (Migrate)

Fab options and Parameters: Fab can set some parameters on the command line to affect the behavior of the fabric, as well as set up the FAB environment variables

-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 default 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, and you can import it components to any of your 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 Printing a colored string

From fabric.colors Import *
Print (Green ("This text is green!"))

2 Some basic operations

Fabric.operations.get (Remote_path, Local_path=none)
Download one or more files from a remote host.remote can be either a directory or a file, CD remotely machine LCD Local Machine

Fabric.operations.local (Command, Capture=false, Shell=none)
Run a command on the local system. Use subprocess to execute commands in the case of Shell=true.

Fabric.operations.open_shell (Command=none)
Invoke a fully interactive shell on the remote end. Interactively invoke the shell of the terminal

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. Upload one or more files, Local_path Local files or directories,

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 context management, primarily with the WITH statement

FABRIC.CONTEXT_MANAGERS.CD (PATH)
Context manager that keeps directory state when calling remote operations, can be used in run sudo get put, CD can only be used on remote servers, local use of LCD.
With CD ('/var/www '):
Run (' ls ') # cd/var/www && ls

FABRIC.CONTEXT_MANAGERS.LCD (PATH)
Context Manager for updating local working directory. With CD, but change the directory locally

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 && prefix the command executed by run or sudo, connect via &&

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

4 Interesting tools

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

In order not to mislead you, some English is not translated, see the Official document: HTTP://DOCS.FABFILE.ORG/EN/1.5/#documentation

Python2.7 Fabric Theory Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.