Introduction to Fabric, a Python library for remote interaction between multiple servers

Source: Internet
Author: User
Tags documentation ssh

In the past two days, I occasionally read this article again and am interested in Fabric. Maybe I can still use it when managing some servers, so I took some time to get to know Fabric.

First, what is Fabric? Fabric is a Python library and command line tool. It can deploy applications or system management tasks that use SSH operations more efficiently (streamlined ).
Fabric is a Python (2.5 or higher) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.
Fabric provides some core and peripheral APIs, see: http://fabric.readthedocs.org/en/1.6/index.html#api-documentation
(Fabric also provides multi-process execution for parallel tasks. It is implemented through the multiprocessing module provided by Python, but it is not thread-safe at present .)

Then, install Fabric and try it out. See http://fabric.readthedocs.org/en/1.6/installation.html
I downloaded the source code and run "python setup. py install" to install it. On Ubuntu, you can also use "sudo apt-get install fabric" to install it directly.

Next, try an example like Helloword.
Edit a file named test-fabric.py with the following content:

The code is as follows: Copy code
From fabric. api import run
 
Def host_type ():
Run ('uname-s ')



Use Fabric to execute it. The command line is as follows:

The code is as follows: Copy code
[Root @ jay-linux jay] # fab-H jay-linux host_type
 
Fatal error: Couldn't find any fabfiles!
 
Remember that-f can be used to specify fabfile path, and use-h for help.
 
Aborting.
[Root @ jay-linux jay] # fab-H jay-linux-f test-fabric.py host_type
[Jay-linux] Executing task 'host _ type'
[Jay-linux] run: uname-s
[Jay-linux] Login password for 'root ':
[Jay-linux] out: Linux
[Jay-linux] out:
 
 
Done.
Disconnecting from jay-linux... done.



When you run the first command, you encounter "Fatal error: Couldn't find any fabfiles !" Error because fabfile is not found in fab.
If you do not use the-f test-fabric.py parameter to specify which fabfile to use, the fab command uses fabfile by default. the py name is used to search for fabfile in the current and its parent appendix. py file (in Linux, it does not search for the root directory at the highest level ).
Therefore, there are three methods to solve the problem of fabfile:
1. "-f your-fabfile.py" to specify your own fabfile;
2. Edit your job in the current directory and name it fabfile. py;
3. You can define the default fabfile in the configuration file of fabric, for example, in ~ /. Specify "fabfile = fab_tasks.py" in the fabricrc file ".
For how Fabric looks up fabfile, see: http://docs.fabfile.org/en/1.6/usage/fabfiles.html#fabfile-discovery
Alternatively, you can directly view find_fabfile (names = None) in the fabric/main. py file in the source code ).

Finally, you can write the host name, user name, password, and other information in fabric. However, it is not recommended to write the plain text in the code. It is better to use the SSH Key for authentication. So I wrote an example using Fabric as follows (in the example named fabfile. in the py file), the Key of my-master is distributed to the machine to be controlled to obtain the SSH key authentication, when operating those machines in the future, you do not need to enter the login password to interact. Note that "@ roles ('Master')" is a function provided by Fabric that allows tasks to be executed on the specified machine.

The code is as follows: Copy code
#! /Usr/bin/python
 
From fabric. colors import red, green
From fabric. context_managers import cd
From fabric. operations import *
From fabric. api import *
 
Env. roledefs = {
'Master': ['My-Master'],
'Slave ': ['vt9', 'vt7', 'vt2']
    }
# Env. hosts = ['My-Master', 'vt9', 'vt7', 'vt1', 'vt2']
# Env. passwords = {'Jay-linux ': '000000', 'My-Master': '000000 '}
Env. password = '000000'
 
Def color ():
Local ('ls-l | wc-L ')
Print (red ("This sentence is red, random T for", bold = True)
+ Green ("these words, which are green ."))
 
Def ctx_mgr ():
With cd ('/var/www '):
Run ('Ls ')
 
@ Roles ('Master ')
Def get_sshkey ():
Get ('/root/. ssh/id_rsa.pub', 'id _ rsa. pub. Master ')
 
@ Roles ('Slave ')
Def put_sshkey ():
With cd ('/tmp '):
Put ('id _ rsa. pub. Master', 'id _ rsa. pub. Master ')
Run ('cat id_rsa.pub.master>/root/. ssh/authorized_keys ')
 
Def do_task ():
Execute (get_sshkey)
Execute (put_sshkey)



Run the following example program:

The code is as follows: Copy code
[Root @ jay-linux jay] # fab do_task
[My-master] Executing task 'get _ sshkey'
[My-master] download:/root/jay/id_rsa.pub.master <-/root/. ssh/id_rsa.pub
[Vt9] Executing task 'put _ sshkey'
[Vt9] put: id_rsa.pub.master->/tmp/id_rsa.pub.master
[Vt9] run: cat id_rsa.pub.master>/root/. ssh/authorized_keys
[Vt7] Executing task 'put _ sshkey'
[Vt7] put: id_rsa.pub.master->/tmp/id_rsa.pub.master
[Vt7] run: cat id_rsa.pub.master>/root/. ssh/authorized_keys
[Vt2] Executing task 'put _ sshkey'
[Vt2] put: id_rsa.pub.master->/tmp/id_rsa.pub.master
[Vt2] run: cat id_rsa.pub.master>/root/. ssh/authorized_keys
 
Done.
Disconnecting from my-master... done.
Disconnecting from vt7... done.
Disconnecting from vt9... done.
Disconnecting from vt2... done.


In short, Fabric is easy to use. You can use Python to define your own tasks. If the number of servers managed is large and the operations executed above are repeated, Fabric should be a good choice.

References:
Fabric official documentation: http://docs.fabfile.org/en/1.6/index.html

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.