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
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor