The fabric of the Python module

Source: Internet
Author: User

Fabric is a Python library and command-line tool designed to make it more efficient and convenient to use the pipelined operations of SSH for application deployment and system management tasks. Fabric provides a basic set of operations for performing local and remote shell commands, uploading and downloading files, including some auxiliary functions, such as driving a running user input or discarding execution.

Fabric remotely performs some application deployment or system maintenance tasks by writing a large number of frequently used SSH operations into a script (fabric.py). Fabric is a Paramiko-like library that is re-encapsulated for Paramiko, so it's easier than using Paramiko.


Benefits of Fabric:


Role definitions

Code easy to read

Encapsulates local, remote operations

Flexible parameters, can even dynamically specify host/role, and concurrent execution (based on multiprocessing)

Full log output


Installation method under Linux:

Use PIP to install

Yum Install Python-pip-ypip Install fabric


Fabric uses the command-line tool fab to perform tasks defined in fabfile.py, which are commonly used in the following configurations and functions:

Common fab command options and Parameters:

-L Display Available tasks

-h specifies host, with multiple hosts separated by commas

-r specifies role, multiple role separated by commas

-p and fractions, default is serial

-W warn_only, default to abort execution and exit by encountering an exception directly

-f Specifies the entry file, the Fab default entry file is: fabfile.py


Common configuration and functions in the fabfile.py file:


Env.host host IP, you can also use the FAB option-H parameter to specify

Env.password ssh Password, if you have set up password-free login, you can ignore

Env.roledefs role groupings, such as: {' Web ': [' x ', ' y '], ' db ': [' Z ']}

Local (' pwd ') execution of native commands

LCD ('/tmp ') switch local directory

CD ('/tmp ') switch remote directory

Run (' uname-s ') execute remote command

sudo (' Service httpd restart ') perform remote sudo, note pty option

env.exclude_hosts=[' 10.1.6.159 ') exclude 10.1.6.159

Fabric.operations.open_shell () Opens the remote shell interface.

Get is download

Put is an upload


Here are some examples:

#/usr/bin/python#coding:utf8from FABRIC.API Import *from fabric.colors import *from fabric.context_managers Import * env . hosts=[' 10.1.6.186 ', ' 10.1.6.159 ']env.password= ' xxxxxx ' def Task1 (): With CD ('/home/guol '): Run (' ls-l ')

Different machines perform different tasks:

#!/usr/bin/pythonfrom fabric.api import *from fabric.colors import *from  fabric.context_managers import * env.roledefs={' web1 ': [' 10.1.6.186 '], ' web2 ': [' 10.1.6.159 ']} env.password= ' xxxxxx '   # #需要配置密码相同,,,,  @roles (' Web1 ') def task1 ():     WITH CD ('/home/guol '):         run (' ls -l ') def @roles (' Web2 ')  task2 ():     print (Green ("I ' M fabric"))  def deploy ():     execute (Task1)     execute (task2) execution result: [Email protected]:/tmp# fab  deploy[10.1.6.186] Executing task  ' Task1 ' [10.1.6.186] run: ls -l[ 10.1.6.186] out: total 0[10.1.6.186] out: -rw-r--r-- 1 root root  0 dec 21 13:32 186-local[10.1.6.186] out:  [10.1.6.159] executing  task  ' Task2 ' I ' M fabric&nbsP;done. Disconnecting from 10.1.6.186... done.


Environment variables for farbic:

There are many environment variables in the fabric, 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


To set up a host list method:


Hosts, in context we call the hosts "host strings"

Strings specified username, hostname, port, etc.

Combo [email protected]:p ort. Username and port can be omitted, the local user and port 22 are used by default.

Strings maps a single host, but sometimes you want to add a bunch of hosts to a group

Roles provides a way to define a series of hosts that can be set by env.rolesdefs

It must be set through Fabfile to be used. env.roledefs[' webservers ' = [' www1 ', ' www2 ', ' WWW3 ']


The type of the parameter passed in the fabric, here is an example:

#!/usr/bin/pythonfrom fabric.api Import *import fabric.operationsfrom fabric.colors import *from fabric.context_ Managers Import *import DateTime env.passwords = {' [email protected]:22 ': ' redhat123456 ', ' [email protected]:22 ': ' Redhat '} @hosts (' [email protected]:22 ') def task1 (): filename = run (' ls/root/my/') #查看远程目录上的文件 (in this case there is only one a.txt in this directory) upload this file name to Ta Sk2 on Go get ('/root/my/* ', '/root/my ') #下载到本地的/root/my directory local (' fab task2:name=%s '% filename) #执行本地命令 and pass the filename this parameter Give Task2@hosts (' [email protected]:22 ') def task2 (name= "): #定义带参数的函数 put ('/root/my/%s '% name, '/root/my ') #把本地的/root/my/ A.txt upload to 192.168.1.2/root/my directory # # # #运行: Fab task1 runs the task2 command separately: Fab task2:name= ' a.txt '


One last example:

#!/usr/bin/env python# -*- coding:utf-8 -*- from fabric.api import env , run,local,hosts,put,puts, cdimport fabric.operationsfrom fabric.colors import * Import datetime  # env.hosts =  [] #下面定义三个主机env. passwords = {' [ Email protected]:22 ': ' Password ',                   ' [email protected]:22 ': ' Password ',                   ' [email protected]:22 ': ' Password '}   @hosts (' [email protected]:22 ') Def uploadmusic ():     put ('./data/*.mp3 ', '/ var/www/html/music/')   #把本地 the mp3 file in the/data/directory to 192.168.10.91  @hosts (' [email protected]:22 ') def  rsyncmusic ():     WITH CD ("/usr/local/tomcat/webapps/"):   #远程执行cd   command, below is the command executed by run         run (' pwd ')         run (' ls /root/')         bak_webapi =  ' tar -zcf webapi_%s.tar.gz  webapi '  % datetime.datetime.now (). Strftime ("%y%m%d%h%m")          run (BAK_WEBAPI)         put ("./data/*.txt", "webapi/WEB-INF/ classes/data/")         run (" rm -rf webapi/web-inf/classes/ Data/index ")         run (" echo  ">/usr/local/tomcat/webapps/ Webapi/web-inf/classes/data/a.txt ")          #fabric. Operations.open_ Shell ("python /root/zhou.py")   @hosts (' [email protected]119.1:22 ') def shellhost ():     fabric.operations.open_shell ()   #远程到119.1, and open the shell




This article is from the Linux learning blog, so be sure to keep this source http://zhou123.blog.51cto.com/4355617/1670055

The fabric of the Python module

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.