O & M manager Fabric usage

Source: Internet
Author: User
Tags python list
Fabric is an SSH command line tool based on Python2.5 or later. it simplifies application deployment and system management tasks of SSH, and provides basic operating components of the system, allows you to install Fabric with local or remote shell commands, including command execution, file upload, download, and complete execution log output.

Fabric supports pip, easy_install, or source code installation, which helps solve the package dependency problem. (select pip or ease_install based on the user environment)
Pip install fabric
Easy_install fabric

Source code installation is not introduced.
Verify the installation result. if the import module does not prompt an exception, 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 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 (): # define a task function and remotely execute the 'uname-s' command run ('uname-s') using the run method ')

If the running result is as follows:

-W: When the command execution fails, a warning is issued, rather than the default task termination.

II. compiling fabfile

The fab command is written in combination with the fabfile. py (other file names must be referenced by-f filename). some command line parameters can be replaced by appropriate methods to make them more flexible, such as "-H 192.168.1.23, 192.168.1.24 ", we can define env. hosts, such as "env. hosts = [192.168.1.23, 192.168.1.24] ". the body of the fabfile consists of multiple custom task functions. different task functions implement different operation Logics. The following describes in detail

3. global attribute settings

The env object defines the global settings of fabfile and supports multiple attributes, including the target host, user, and password roles. the attributes are described as follows:

Env. host, which defines the target host. it can be expressed by IP address or host name and defined in the form of Python list, such as env. hosts = ['2017. 168.1.23, 192.168.1.24 ']. env. exculde_hosts to exclude the specified host, such as env. exclude_hosts = ['2014. 192. 168.1.23 '] env. user, which defines the user name, such as env. user = "root" env. port, which defines the target host port, such as env. port = '22' env. password, which defines the password, such as env. password = '000000' env. the passwords function is the same as the password function. The difference lies in the application scenarios of different hosts with different passwords. Note that when configuring passwords, you need to configure user, host, port, and other information, such as env. passwords = {'root @ 192.168.1.21: 22 ': '000000', 'root @ 192.168.1.23: 22': '000000', 'root @ 192.168.1.24: 23': '000000 ',} env. gateway, which defines the IP address of the gateway (transit, Bastion host), such as env. gateway = '2017. 168.1.1 'env. roledefs defines a role Group. for example, the web group and the db Group host are distinguished as follows: env. roledefs = {'webservers': ['2017. 168.1.21 ', '2017. 168.1.22 ', '2017. 168.1.23 '], 'dbservers': ['2017. 168.1.24 ', '2017. 168.1.25 '],}

The python modifier is used for reference. The task function below the role modifier is in its scope. The following is 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)

Execute the command fab deploy to execute different task functions for different roles.

Common APIs

Fabric provides a simple but powerful set of fabric. api commands, which can be called to meet most application scenarios. Fabric supports the following common methods and instructions:

Local: execute local commands, such as local :( 'uname-s'); LCD, switch to local directory, such as LCD :( '/home'); cd, switch to remote directory, for example, cd :( '/data/logs/'); run: execute remote commands, such as run ('free-M') sudo and sudo: sudo ('/etc/init. d/httpd start'); put: Upload local files to a remote host, for example, put ('/home/user.info', '/data/user.info'); get, download files from the remote host to the local machine, for example, get ('/home/user.info', '/data/user.info'); prompt to obtain user input information, such: prompt ('Please input user password: '); confirm, to obtain prompt information for confirmation, such as: confirm ('test failed, Continue [Y/N]'); reboot, restart a remote host, such as reboot (); @ task, Function modifier. the function of the identifier can be called by fab. The non-flag is invisible to fab and is purely business logic. @ runs_once, function modifier. the identifier function is executed only once and is not affected by multiple hosts;

Example 1: View local and remote host information
In this example, call the local () method to execute the local command and add the "@ runs_once" modifier to ensure that the task function is executed only once. Call the run () method to execute a remote command,

#! /Usr/bin/env python #-*-coding: UTF-8-*-from fabric. api import * env. user = 'root' env. hosts = ['2017. 168.1.43 ', '2017. 168.1.23 ', '2017. 168.1.24 '] env. port = '22' env. password = '000000' @ runs_once # View local system information. when multiple hosts run def local_task () only once: # local task function local ('uname-') def remote_task (): with cd ('/data'): # with is used to make subsequent expression statements inherit the current state, run ('ls-L ')

Use the fab command to call the local_task task function, as shown in.

This example uses the "@ task" modifier to mark that the entry function go () can be used externally, with the "@ runs_once" character waiting to receive user input, and finally calls worktask () task functions implement remote command execution,

#! /Usr/bin/env python #-*-coding: UTF-8-*-from fabric. api import * env. user = 'root' env. hosts = ['2017. 168.1.23 ', '2017. 168.1.24 '] env. password = '000000' @ runs_once # during host traversal, only one of them starts from this function def input_raw (): return prompt ("please input direcotry name :", default = "/home") def worktask (dirname): run ("ls-l % s" % dirname) @ taskdef go (): getdirname = input_raw () worktask (getdirname)

In this example, a remote directory name is entered dynamically. in the directory list retrieval function, because we only need to enter the name once and then display the list of directories on all hosts, A sub-function input_raw (configured at the same time) @ runs_once modifier is called to achieve this purpose. the execution result is as follows:

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 confirmenv. hosts = ['2017. 168.1.23 ', '2017. 168.1.24 '] # if the passwords of all hosts are different, you can use env. the passwords dictionary variables specify env one by one. passwords = {'root @ 192.168.1.23: 22 ': '000000', 'root @ 192.168.1.24: 22': '000000 ',} lpackpath = "/home/a.tar.gz" rpackpath = "/tmp/install" @ taskdef put_task (): run ("mkdir-p/tm P/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! ") @ Taskdef run_task (): with cd ("/tmp/install "): run (" tar-zxvf a.tar.gz ") @ taskdef go (): put_task () run_task ()

For more information about how to use Fabric in the O & M manager, refer to PHP Chinese network!

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.