search
HomeBackend DevelopmentPython TutorialHow to use the operation and maintenance manager Fabric

Fabric installation

Fabric supports pip, easy_install or source code installation, which is very convenient to solve package dependency problems. (According to the user environment, you can choose pip or ease_install)
pip install fabric
easy_install fabric

The source code installation will not be introduced.
Verify the installation result. If no exception is prompted when importing the module, the installation is successful:

root@Python_S6:~# python
Python 2.7.5+ (default, Sep 19 2013, 13: 48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import fabric
>>>

The official website provides a simple getting started example:

root@Python_S6:/home/chart7/test/fabric# cat farbic.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import run
  
def host_type(): #定义一个任务函数,通过run方法实现远程执行'uname -s'命令
  run('uname -s')

If the running result is as shown in the figure below

How to use the operation and maintenance manager Fabric

The default file name referenced by the command is fabfile.py. If a non-default file name is used, it needs to be specified by '-f', such as: fab -H 192.168.1.23,192.168.1.24 -f host_type .py host_type, if the management machine and the target host are not configured with key authentication trust, you will be prompted to enter the login password of the corresponding account of the target host.

1. Commonly used parameters of fab

As the command entrance of the Fabric program, fab provides a wealth of parameter calls. The command format is as follows:
fab [options] [: arg1,arg2=val2,host=foo,hosts='h1;h2',....]
The following lists several commonly used parameters, and you can use fab -help to view more parameters.
-l , display the defined task function name;
-f, specify the fab entry file, the default entry file name is fabfile.py;
-g, specify the gateway device, such as the bastion host environment, just fill in the bastion host IP ;
-H, specify the target host, multiple hosts are separated by ',';
-P, run multiple host tasks in asynchronous parallel mode, the default is serial operation;
-R, specify role (role), use role names to distinguish devices of different business groups;
-t, set the device connection timeout;
-T, set the remote host command execution timeout;
-w, when the command execution fails , issue a warning instead of terminating the task by default

2. Writing fabfile

The fab command is used in conjunction with the fabfile.py we wrote (other file names must be referenced by adding -f filename) , some command line parameters can be replaced by corresponding methods to make them more flexible, such as "-H 192.168.1.23,192.168.1.24". We can achieve this by defining env.hosts, such as "env.hosts=[192.168 .1.23,192.168.1.24]"The main body of .fabfile is composed of multiple customized task functions. Different task functions implement different operation logic. The following is a detailed introduction

3. Global attribute settings

The env object is used to define the global settings of the fabfile and supports multiple attributes, including target host, user, and password role. The description of each attribute is as follows:

env.host,定义目标主机,可以用IP或主机名表示,以Python的列表形式定义,如env.hosts=['192.168.1.23,192.168.1.24'].
env.exculde_hosts,排除指定主机,如env.exclude_hosts=['192.168.1.23']
env.user,定义用户名,如env.user="root"
env.port,定义目标主机端口,如env.port = '22'
env.password,定义密码,如env.password='123456'
env.passwords,与password功能一样,区别在于不同主机不同密码的应用场景,需要注意的是,配置passwords时需要配置用户,主机,端口等信息,如:env.passwords = {'root@192.168.1.21:22':'123456',
'root@192.168.1.23:22':'3234234',
'root@192.168.1.24:23':'09887',
}
env.gateway,定义网关(中转,堡垒机)IP,如env.gateway = '192.168.1.1'
env.roledefs,定义角色分组,比如web组与db组主机区分开来,定义如下:
env.roledefs = {
'webservers':['192.168.1.21','192.168.1.22','192.168.1.23'],
'dbservers':['192.168.1.24','192.168.1.25'],
}

Use the python modifier when referencing. The task function under the role modifier has its scope. Let's look at an example:

@roles('webservers')
def webtask():
  run('/etc/init.d/nginx start')
@roles('dbservers'):
def dbtask():
  run('/etc/init.d/mysql start')
@roles('webservers','dbservers')
def publictask():
  run('uptime')
def deploy():
  execute(webtask)
  execute(dbtask)
  execute(publictask)

By executing fab deploy in the command, different roles can execute different task functions.

Commonly used API

Fabric provides a set of simple but powerful fabric.api command sets. Simply calling this API can complete most application scenario requirements. Fabric supports common methods and The description is as follows:

local,执行本地命令,如local:('uname -s');
lcd,切换本地目录,如lcd:('/home');
cd,切换远程目录,如cd:('/data/logs/');
run,执行远程命令,如:run('free -m')
sudo,sudo方式执行远程命令,如:sudo('/etc/init.d/httpd start');
put,上传本地文件到远程主机,如:put('/home/user.info','/data/user.info');
get,从远程主机下载文件到本地,如:get('/home/user.info','/data/user.info');
prompt,获得用户输入信息,如:prompt('please input user password:');
confirm,获得提示信息确认,如:confirm('Test failed,Continue[Y/N]');
reboot,重启远程主机,如reboot();
@task,函数修饰符,标识符的函数为fab可调用,非标记对fab不可见,纯业务逻辑;
@runs_once,函数修饰符,标识符的函数只会执行一次,不受多台主机影响;

Example 1: View local and remote host information
This example calls the local() method to execute local commands, and adds the "@runs_once" modification to ensure that the task function is only executed once. Call the run() method to execute remote commands.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import *
env.user = 'root'
env.hosts = ['192.168.1.43','192.168.1.23','192.168.1.24']
env.port = '22'
env.password = '123456'
  
@runs_once #查看本地系统信息,当有多台主机时只运行一次
def local_task(): #本地任务函数
  local('uname -a')
  
def remote_task():
  with cd('/data'): #with的作用是让后面的表达式语句继承当前状态,实现cd /var && ls -l的效果
    run('ls -l')

Call the local_task task function through the fab command respectively. The running effect is as shown in the figure below

How to use the operation and maintenance manager Fabric

The results show [192.168.1.23] Executing task 'local_task', but in fact the task is not executed on the host 192.168.1.23, but the execution effect of 'uname -a' local to the Fabric host is returned.

The execution result of calling the remtoe_task task function is shown in the figure below

How to use the operation and maintenance manager Fabric

Example 2; dynamically obtain the remote directory list
This example uses the "@task" modifier to mark the entry function go () can be used externally, with the "@runs_once" symbol to wait for user input, and finally call the worktask() task function to implement remote command execution.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import *
env.user = 'root'
env.hosts = ['192.168.1.23','192.168.1.24']
env.password = '123456'
@runs_once #在主机遍历过程中,只有一台出发此函数
def input_raw():
  return prompt("please input direcotry name:",default="/home")
  
  
def worktask(dirname):
  run("ls -l %s" %dirname)
  
@task
def go():
  getdirname = input_raw()
  worktask(getdirname)

This example implements a dynamic input remote Directory name, in the function of obtaining the directory list, since we only require input once, and then display the list information of the directory on all hosts, a sub-function input_raw (configured at the same time) @runs_once modifier is called to achieve this purpose. The execution results are as follows Figure

How to use the operation and maintenance manager Fabric

File upload and execution

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
env.hosts=['192.168.1.23','192.168.1.24']
#假如所有主机密码都不一样,可以通过env.passwords字典变量一一指定
env.passwords = {
  'root@192.168.1.23:22': '123456',
  'root@192.168.1.24:22': '123456',
}
  
lpackpath="/home/a.tar.gz"
rpackpath="/tmp/install"
  
@task
def put_task():
  run("mkdir -p /tmp/install")
  with settings(warn_only=True):
    result = put(lpackpath, rpackpath)
  if result.failed and not confirm("put file failed, Continue[Y/N]?"):
    abort("Aborting file put task!")
  
@task
def run_task():
  with cd("/tmp/install"):
    run("tar -zxvf a.tar.gz")
  
@task
def go():
  put_task()
  run_task()

For more articles related to how to use the operation and maintenance manager Fabric, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool