Python's batch remote administration and deployment tool Fabric usage instance

  • 2020-04-02 14:31:39
  • OfStack

This article illustrates the use of Fabric for Python's batch remote administration and deployment tool. Share with you for your reference. The details are as follows:

Fabric is a very powerful batch remote management and deployment tool in Python that is often used to perform batch SSH tasks on multiple remote PCS.

The common usage methods are summarized as follows:

1. First, write the batch task to a fabfile.py

# -*- coding:utf-8 -*-  
 
from fabric.api import run, local, roles, env, cd 
env.hosts=[ 
    '192.168.1.110', 
    '192.168.1.111', 
    '192.168.1.112' 

env.user="username" 
env.password="password" 
env.port=22 
#env.parallel=True 
#env.skip_bad_hosts=True 
#env.timeout=1 
#env.warn_only=True 
 
# local Used locally PC Execute the command . 
# run Used at a distance PC Execute the command . 
def ls(): 
    with cd('/home/workspace/project'): 
        local('touch 1.log') 
    with cd('/home/workspace/project2'): 
        local('touch 2.log')  
 
#@parallel, You can set whether to execute in parallel  
#@serial 
def pull(): 
    with cd('/home/workspace/project'): 
        run('git pull') 
 
def clean(): 
    with cd('/home/workspace/project'): 
        run('bash clean.sh') 
 
@hosts('192.168.1.113') 
def robot(device): 
    with cd('/home/workspace/project'): 
        run('bash run.sh %s robot && sleep 1' % device)

This is a simple fabfile.py, where the functions defined correspond to an executable command in fab.
There are two small caveats:

A. In the run.sh of the remote machine, if you want to execute some non-system common tools, it is best to specify the absolute path, and you can use the nohup approach appropriately.

B. It is best to add sleep after executing other scripts or commands to prevent Fabric from prematurely closing the session connected to the remote PC and failing to execute the task.

2. Execution process: the fabfile.py file in the current directory will be selected by default by fabric execution.

fab clean
fab pull
fab robot:hosts="192.168.1.115",device=5560

A specified remote PC can be passed to fabric through the hosts parameter, which has a higher priority than env.hosts.

You can also pass arguments, such as device, to commands in fab.

In addition, you can specify other fabric files by fab-f otherfabfile.py clean.

If parallel execution is required, you can also pass parameters such as fab-p-z 15 pull, which represents the number of PCS executed in parallel.

Above, just some simple usage, if you need more advanced usage, can focus on the project making homepage at https://github.com/fabric/fabric.

I hope this article has helped you with your Python programming.


Related articles: